PHP strings, sprintf, and regular expressions
Format text with sprintf, split and join strings, and match patterns with preg functions.
<?php
$name = "Programonic";
echo strlen($name), " ", substr($name, 0, 7), " ", strpos($name, "m"), "\n";
echo sprintf("%05.1f|%-8s|%'*8s|%x", 3.14159, "left", "right", 255), "\n";
$parts = explode(",", "a,b,,c");
echo count($parts), " ", implode("-", $parts), "\n";
echo str_contains("haystack", "st") ? "yes" : "no", " ", ucfirst("php"), " ", strrev("abc"), "\n";
if (preg_match('/^(\d{4})-(\d{2})-(\d{2})$/', "2024-03-15", $m)) {
echo $m[1], "/", $m[2], "/", $m[3], "\n";
}
echo preg_replace('/\s+/', ' ', "too many spaces"), "\n";
echo str_pad("7", 3, "0", STR_PAD_LEFT), "\n";11 Program 6 003.1|left |***right|ff 4 a-b--c yes Php cba 2024/03/15 too many spaces 007
Explanation
PHP strings come with a large set of functions. strlen gives the length in bytes, substr extracts part of the string, and strpos finds a position or returns false. explode splits a string into an array and implode joins an array back together. str_contains, ucfirst, strrev, and str_pad cover many everyday tasks.
sprintf builds text from a format string. %05.1f is a float with one decimal, zero-padded to width 5, %-8s pads a string on the right, %'*8s pads it on the left with stars, and %x prints hexadecimal. The preg_ functions use Perl-compatible regular expressions: preg_match fills an array with the matched groups, and preg_replace substitutes matches. Remember that strlen counts bytes, so multibyte text needs the mb_ functions.
Explore the dry run
<?php$name = "Programonic";echo strlen($name), " ", substr($name, 0, 7), " ", strpos($name, "m"), "\n";echo sprintf("%05.1f|%-8s|%'*8s|%x", 3.14159, "left", "right", 255), "\n"; $parts = explode(",", "a,b,,c");echo count($parts), " ", implode("-", $parts), "\n";echo str_contains("haystack", "st") ? "yes" : "no", " ", ucfirst("php"), " ", strrev("abc"), "\n"; if (preg_match('/^(\d{4})-(\d{2})-(\d{2})$/', "2024-03-15", $m)) { echo $m[1], "/", $m[2], "/", $m[3], "\n";}echo preg_replace('/\s+/', ' ', "too many spaces"), "\n";echo str_pad("7", 3, "0", STR_PAD_LEFT), "\n";Follow the example
Start to inspect the source, values, and output. These prepared steps explain the published sample; grouped loop steps describe multiple iterations.
View the complete dry-run table
| Step / line | What happens | State after step | Output so far |
|---|---|---|---|
| Length 11, the first seven characters, and the position of the first m. | — | 11 Program 6 | |
| A zero-padded float, a left-aligned string, a star-padded string, and hexadecimal. | — | 11 Program 6 003.1|left |***right|ff | |
| explode keeps the empty piece between the commas, so there are four parts. | — | 11 Program 6 003.1|left |***right|ff 4 a-b--c | |
| Three small helpers in one line. | — | 11 Program 6 003.1|left |***right|ff 4 a-b--c yes Php cba | |
| preg_match stored the three captured groups in $m after the whole match at $m[0]. | — | 11 Program 6 003.1|left |***right|ff 4 a-b--c yes Php cba 2024/03/15 | |
| Runs of white space become single spaces. | — | 11 Program 6 003.1|left |***right|ff 4 a-b--c yes Php cba 2024/03/15 too many spaces | |
| Left-pad with zeros to width 3. | — | 11 Program 6 003.1|left |***right|ff 4 a-b--c yes Php cba 2024/03/15 too many spaces 007 |
Cost and common mistakes
Most string functions are O(n) in the length of the string.
- strpos returns false when nothing is found, and false == 0 in a loose comparison. Compare with === false.
- Double-quoted strings interpolate variables and escape sequences; single-quoted strings do not. Regular expressions are usually written in single quotes for that reason.
- strlen and substr work on bytes. A string with accented letters or emoji needs mb_strlen and mb_substr.
Try it yourself
What does sprintf("%03d", 5) return?
Reveal answer and reasoning
"005": the integer is zero-padded to a width of three digits.