Strings and regular expressions
String functions, sprintf, explode / implode, multibyte text with mb_*, and preg_* regular expressions.
Runs in Zerethon IDE · PHP 8.4
Official PHP documentation ↗
main.php
<?php
$name = 'Ada Lovelace';
echo strtoupper($name), ' ', strlen($name), ' ', substr($name, 0, 3), ' ', strpos($name, 'Love'), "\n";
echo trim(' padded ') . '|', ' ', str_contains($name, 'Love') ? 'yes' : 'no', ' ', str_replace('Ada', 'Augusta', $name), "\n";
echo implode('-', explode(',', 'a,b,c')), ' ', sprintf('%.2f|%5d|%03d', 3.14159, 42, 7), "\n";
echo strlen('Việt'), ' ', mb_strlen('Việt'), ' ', mb_strtoupper('việt'), "\n";
if (preg_match('/order (\d+) pending/', 'Order 12 shipped, order 7 pending', $m)) {
echo $m[1], "\n";
}
preg_match_all('/\d+/', 'a1b22c333', $all);
echo implode(',', $all[0]), ' ', preg_replace('/\d+/', '#', 'a1b22c'), "\n";
Output
ADA LOVELACE 12 Ada 4 padded| yes Augusta Lovelace a-b-c 3.14| 42|007 6 4 VIỆT 7 1,22,333 a#b#c
strlencounts bytes; for UTF-8 text (accents, Vietnamese, emoji) use themb_*functions.- Write regular expressions in single quotes, with delimiters:
'/\d+/'. strposreturns0for a match at the start andfalsefor none — compare with!== false, or usestr_contains.