Simple demo of preg_match and preg_match_all"; $pattern = array("/matches/", "/catch/", "/atch/", "/matches/i"); $subject = "What matches here! Matches there? We don't need no matches."; echo ""; echo "matching "; print_r($pattern); echo "
in : $subject
"; echo "


"; foreach ($pattern as $key): if (preg_match($key, $subject, $result, PREG_OFFSET_CAPTURE)): echo "MATCH: $key was found: \n"; print_r($result); echo "
"; else: echo "MATCH: $key not found
\n"; endif; if (preg_match_all($key, $subject, $result)): echo "MATCH ALL: $key was found: \n"; print_r($result); echo "
"; else: echo "MATCH ALL: $key not found
\n"; endif; endforeach; echo "
";; echo "

Simple character classes

"; $pattern = "/[aeiou][1234567890][a-z]/"; $subject = "ae12abc r2d2 a1steaksauce"; echo ""; echo "matching $pattern
in: $subject"; echo "


"; if (preg_match($pattern, $subject, $result)): echo "MATCH: $pattern was found: \n"; print_r($result); echo "
";; endif; echo "
";; echo "

Using repetition together with character classes

"; $pattern = "/[aeiou]+[1234567890]*[a-z]?/"; echo ""; echo "matching $pattern
in: $subject"; echo "


"; if (preg_match_all($pattern, $subject, $result)): echo "MATCH ALL: $pattern was found: \n"; print_r($result); echo "
";; endif; $pattern = "/\d+\.\d{5}/"; $subject = "3 .14159 3.1415 3.14159"; echo "
"; echo "matching $pattern
in: $subject"; echo "


"; if (preg_match_all($pattern, $subject, $result)): echo "MATCH ALL: $pattern was found: \n"; print_r($result); echo "
";; endif; echo "

Using submatches as part of an overall match.

"; //Note that the back references have a double backslash $pattern = array("/(\w+)\\1/", "/(\w+)(.*)(\\1)/", "/(\w+)\\1\b/"); $subject = array("catcat", "abc123abc", "matchmatchhere"); echo ""; echo "matching: "; print_r($pattern); echo "
in: "; print_r($subject); echo "

"; echo ""; foreach ($pattern as $key): foreach ($subject as $sub): if (preg_match($key, $sub, $result)): echo "MATCH: $key matches "; print_r($result); echo "
"; endif; endforeach; endforeach; echo "

Simple demo of preg_replace

"; $subject = "{mydate} = 1995-3-24"; $pattern = array ('/(19|20)(\d{2})-(\d{1,2})-(\d{1,2})/', '/^\s*{(\w+)}\s*=/'); $replace = array ('\3/\4/\1\2', '$\1 ='); echo ""; echo "replacing :"; print_r($pattern); echo "
"; echo "with: "; print_r($replace); echo "
in : $subject
"; echo "

"; echo preg_replace($pattern, $replace, $subject); echo "
";; ?>