Working with strings in PHP

Beginner  Nov 3, 2026

The string functions you will reach for every day.

Working with strings in PHP
The steps of this tutorial at a glance.
The steps of this tutorial at a glance.

Length, case, trim

<?php
$s = '  Hello PHP World  ';
$t = trim($s);                 // 'Hello PHP World'
echo strlen($t);               // 15
echo strtoupper($t);           // HELLO PHP WORLD
echo ucwords('mary jane');     // Mary Jane
How the code in this section fits into the page.
How the code in this section fits into the page.

Search and cut

echo str_contains($t, 'PHP') ? 'yes' : 'no';   // yes
echo substr($t, 0, 5);                         // Hello
echo strpos($t, 'PHP');                        // 6
echo str_replace('World', 'Team', $t);

Split and join

$parts = explode(',', 'a,b,c');    // ['a','b','c']
echo implode(' | ', $parts);       // a | b | c

Non-English text

strlen('اردو') counts bytes, not letters. For Urdu, Arabic or accented text use the mb_ versions: mb_strlen, mb_substr, mb_strtoupper.

Formatting

echo sprintf('%05d', 42);          // 00042
echo number_format(1234567.891, 2); // 1,234,567.89
Formatting
Formatting

Safety reminder

Strings that come from users must be escaped with htmlspecialchars() before you print them in HTML.

More tutorials