How to use regular expressions

Regular expressions function

preg_match($pattern, $string)

How to use the preg_match() function

How to create a regular expression

$pattern = '/Harris/';

Two strings to test

$author = 'Ray Harris'; 
$editor = 'Joel Murach';

How to use the preg_match() function to search for the pattern

$author_match = preg_match($pattern, $author); // $author_match is 1
$editor_match = preg_match($pattern, $editor); // $editor_match is 1

How to test for errors in a regular expression

if ($author_match === false) {
  echo 'Error testing author name.'; 
} else if ($author_match === 0) { 
  echo 'Author name does not contain Harris.';
} else {  
  echo 'Author name contains Harris.
}

A case-insensitive regular expression

How to create a case-insensitive regular expression

$pattern = '/murach/i';

How to use a case-insensitive regular expression

$editor_match = preg_match($pattern, $editor);

Description

Back