01 · THE IDEAREAD → TRY → LEARN
Why chain string functions?
Real text is messy. Users add stray spaces, type in random case, and leave gaps in lists. PHP has a large family of string functions, and the useful skill is not memorising all of them but chaining a few small ones into a predictable pipeline. Each function takes a string and returns a new string or array. PHP strings are values, so the original is never modified.
Step 1: trim and case
trim() removes whitespace from both ends. ltrim() and rtrim() clean only one side. strtolower() and strtoupper() change ASCII letters. A common cleaning pipeline reads from the inside out: trim first, then normalise case.
$raw = " PHP Strings ";
$clean = strtolower(trim($raw));
echo json_encode([$raw, $clean, strlen($raw), strlen($clean)], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), PHP_EOL;[" PHP Strings ","php strings",15,11]
The example prints both versions along with their byte lengths. strlen() counts bytes, which equals characters for plain ASCII text like this.
Step 2: split and join
explode() turns a string into an array using a separator. implode() does the reverse. Together they let you clean each piece of a list. Combine them with array_map() and array_filter() to trim every item and drop the empty ones.
$csv = "red, green ,blue,, yellow";
$parts = array_map('trim', explode(',', $csv));
echo json_encode($parts, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), PHP_EOL;
$filtered = array_values(array_filter($parts, fn($p) => $p !== ''));
echo implode(' | ', $filtered), PHP_EOL;
echo json_encode(explode(',', ''), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), PHP_EOL;["red","green","blue","","yellow"] red | green | blue | yellow [""]
The last line is important. Splitting an empty string does not give an empty array. It gives an array holding one empty string. That is why the filtering step matters: it turns that case into an empty list, so no special branch is needed.
Step 3: reshape the result
Once text is clean you can reshape it. ucwords() capitalises each word, str_replace() swaps substrings, substr() takes a slice, str_pad() extends a string to a fixed width, and str_contains() tests for a substring.
$title = ucwords(strtolower(trim(" mIxEd cAsE tEXT ")));
echo $title, PHP_EOL;
echo str_pad(substr($title, 0, 5), 8, '.'), PHP_EOL;
echo str_replace(' ', '_', $title), PHP_EOL;
echo str_contains($title, 'Case') ? 'yes' : 'no', PHP_EOL;Mixed Case Text Mixed... Mixed_Case_Text yes
Notice the order. Lowercasing before ucwords() gives a consistent result, because ucwords() only raises the first letter of each word and leaves the rest alone.
Handling empty strings
A well-built pipeline treats empty input as just another input. If the pieces are chosen well, an empty or whitespace-only string flows through and comes out empty. Avoid if ($text === '') return ''; at the top unless you really need it. Functions such as preg_split() with the PREG_SPLIT_NO_EMPTY flag return an empty array for blank input, and implode() of an empty array returns an empty string.
Worked plan for the exercise
You will write slugify_title(string $text): string, which turns a title into a hyphenated lowercase slug:
- Trim the text and lowercase it.
- Split it on any run of whitespace, dropping empty pieces. Spaces, tabs and newlines all count as separators.
- Join the pieces with
-.
For example, " Hello World " becomes "hello-world", and " " becomes "".
Common mistakes
- Replacing single spaces with
str_replace(). Two spaces in a row then give a double hyphen, and tabs are missed. - Forgetting to trim, which leaves hyphens at the start or end of the slug.
- Assuming
explode()on an empty string returns[]. - Using
strtolower()on non-ASCII text and expecting full Unicode behaviour. For multibyte text, look at themb_functions instead.
Recap
Chain small string functions from the inside out. Use trim() and strtolower() to normalise, explode() and implode() to work on pieces, and filter empty pieces so blank input needs no special case.
Strings
- Combine trim, strtolower and string operations
- Handle empty strings without special-case output