View Category

Check if a string matches a regular expression

Display "ok" if "Hello" matches /[A-Z][a-z]+/
php
if(ereg('[A-Za-z]+', 'Hello')) {
echo "ok";
}
if(preg_match('/[A-Za-z]+/', 'Hello')>0) {
echo "ok";
}

Check if a string matches with groups

Display "two" if "one two three" matches /one (.*) three/
php
preg_match('/one (.*) three/', 'one two three', $matches);
echo $matches[1];
ereg('one (.*) three', 'one two three', $regs);
echo $regs[1];

Check if a string contains a match to a regular expression

Display "ok" if "abc 123 @#$" matches /\d+/
php
if (preg_match("/\d+/", "abc 123 @#$"))
echo "ok";

Loop through a string matching a regex and performing an action for each match

Create a list [fish1,cow3,boat4] when matching "(fish):1 sausage (cow):3 tree (boat):4" with regex /\((\w+)\):(\d+)/
php
preg_match_all("/\((\w+)\):(\d+)/", "(fish):1 sausage (cow):3 tree (boat):4", $matches);
for ($i=0, $c=count($matches[0]); $i < $c; $i++) {
$list[] = $matches[1][$i].$matches[2][$i];
}

Replace the first regex match in a string with a static string

Transform "Red Green Blue" into "R*d Green Blue" by replacing /e/ with "*"
php
echo preg_replace('/e/', '*', "Red Green Blue", 1);

Replace all regex matches in a string with a static string

Transform "She sells sea shells" into "She X X shells" by replacing /se\w+/ with "X"
php
echo preg_replace('/se\w+/', 'X', 'She sells sea shells');

Replace all regex matches in a string with a dynamic string

Transform "The {Quick} Brown {Fox}" into "The kciuQ Brown xoF" by reversing words in braces using the regex /\{(\w+)\}/.
php
// We have to use the e-modifier
preg_replace("/\{(\w+)\}/e", "''.strrev('\\1').''", "The {Quick} Brown {Fox}");
// We could use a Closure (callback function)
preg_replace_callback("/\{(\w+)\}/", function($m) { return strrev($m[1]); }, "The {Quick} Brown {Fox}");