String Functions
Strings have appeared in every chapter so far, but always as fixed pieces of text. This chapter covers PHP's large built-in library of string functions — the everyday tools for working with text that isn't already in exactly the shape you need.
Length and Case
Searching Inside a String
strpos() correctly returns 0. But 0 behaves as "false-ish" in a loose boolean check, making if (!strpos(...)) wrongly treat "found at position 0" the same as "not found at all". Always write strpos($str, $search) === false to test specifically for "not found", never a plain truthy/falsy check.
Slicing and Replacing
Splitting and Joining
explode() turns a string into an array by splitting on a delimiter; implode() does the reverse — joining an array's elements into a single string with a chosen separator between them.
Formatting Output — sprintf
sprintf() builds a formatted string using placeholders — %s for strings, %d for integers, %.2f for a float fixed to 2 decimal places. It's especially useful for money values, where plain string interpolation can't reliably guarantee a consistent number of decimal places.
| Function | What it does |
|---|---|
| strlen($s) | Length in characters |
| strtoupper / strtolower | Change case |
| str_contains / strpos | Search inside a string |
| substr($s, $start, $len) | Extract part of a string |
| str_replace($search, $replace, $s) | Replace occurrences |
| trim($s) | Remove leading/trailing whitespace |
| explode($delim, $s) | String → array |
| implode($glue, $arr) | Array → string |
| sprintf($format, ...) | Build a precisely formatted string |
strlen() or strtoupper() treat it identically either way.
Coding Challenges
Take the string " philip osztromok " (note the extra spaces). Trim it, then use ucwords() to capitalise each word properly, and echo the final cleaned-up result along with its length using strlen().
Given the string "2026-06-20", use explode() to split it into year, month, and day parts. Then use sprintf() to echo it back out in the format "20/06/2026" (day/month/year, UK style).
Write a function censorWord($sentence, $word) that uses str_replace() to replace every occurrence of $word in $sentence with asterisks matching its length (e.g. "cat" becomes "***"). Test it on a sentence containing the target word twice.
Chapter 7 Quick Reference
- strlen, strtoupper/strtolower, ucfirst, ucwords — length and case
- str_contains, strpos, str_starts_with — searching; use === false to test "not found" with strpos
- substr($s, $start, $len) — extract a portion of a string
- str_replace, trim — replacing and cleaning up whitespace
- explode / implode — string ↔ array conversions
- sprintf($format, ...) — precise formatted output, especially for numbers/money
- Next chapter: superglobals — $_GET, $_POST, and $_SERVER, and handling form input