How to create complex patterns

HOw to match string positions

Pattern Matches
^ The beginning of the string (use \^ to match a caret)
$ The end of the string (use \$ to match a dollar sign)
\b The beginning or end of a word (must not be inside brackets)
\B A position other than the beginning or end of a word

String positions

      $author = 'Ray Harris'; 
      preg_match('/^Ray/', $author); // Returns 1
      preg_match('/Harris$/', $author); // Returns 1
      preg_match('/^Harris/', $author); // Returns 0
      $editor = 'Anne Boehm';
      preg_match('/Ann/', $editor); // Returns 1
      preg_match('/Ann\b/', $editor);  // Returns 0
      

How to group and match subpatterns

Pattern Matches
(subpattern) Creates a numbered subpattern group (use \( and \) to match a parenthesis)
(?:subpattern) Creates an unnumbered subpattern group
| Matches either the left or right subpattern
\n Matches a numbered subpattern group

Pattern Matches
^ The beginning of the string (use \^ to match a caret)
$ The end of the string (use \$ to match a dollar sign)
\b The beginning or end of a word (must not be inside brackets)
\B A position other than the beginning or end of a word

Subpatterns

      $name = 'Rob Robertson'; 
      preg_match('/^(Rob)|(Bob)\b/', $name); // Returns 1
      preg_match('/^(\w\w\w) \1/', $name); // Returns 1
      

How to match a repeating pattern

Pattern Matches
{n} Pattern must repeat exactly n times (use \{ and \} to match a brace)
{n,} Pattern must repeat n or more times
{n,m} Subpattern must repeat from n to m times Zero or one of the previous subpattern (same as {0,1})
+ One or more of the previous subpattern (same as {1,})
* Zero or more of the previous subpattern (same as {0,})

Repeating patterns

      $phone = '559-555-6627'; 
      preg_match('/^\d{3}-\d{3}-\d{4}$/', $phone); // Returns 1
      $fax = '(559) 555-6635'; 
      preg_match('/^\(\d{3}\) ?\d{3}-\d{4}$/', $fax); // Returns 1
      preg_match($phone_pattern, $fax); // Returns 1
      $phone_pattern = '/^(\d{3}-)|(\(\d{3}\) ?)\d{3}-\d{4}$/';
      preg_match($phone_pattern, $phone) // Returns 1
      

Back