PHP regex cheat sheet — metacharacters, groups, lookaround, modifiers

Regular expressions

  • Metacharacters

    • . — any character except newline
    • \w — word characters (letters, digits, underscore; may include CJK depending on engine/settings)
    • \s — whitespace
    • \b — word boundary
    • * — 0 or more of the preceding atom
    • + — 1 or more
    • ? — 0 or 1
    • ^ — start of string (or negation inside [])

      example: capture anchor text (non-greedy inner match)
              $reg='#<a[^>]*>([^<>]*)<\/a>#';
              $str="<a href='ssss'>some</a>other<a href='ddd'>some</a>";
              $res=preg_match_all($reg,$str,$m);
    
  • Character class

    • [] — match one character; ?, *, ., {} usually need no extra escaping inside
  • Alternation

    • | — branches (can be multi-character); order matters
  • Capturing groups

    • (exp) — match exp and capture into a numbered group
    • (?<name>exp) — named capture; back-reference with \k<name>
    • (?:exp) — match without capturing (no group number)

    Group numbers are assigned left to right: unnamed groups first, then named ones.


    • (?=exp) — position before exp (lookahead)
    • (?<=exp) — position after exp (lookbehind)
    • (?!exp) — position where exp does not follow (negative lookahead)
    • (?<!exp) — position where exp does not precede (negative lookbehind)

    Assertions match a position, not the text of exp.


      example: thousands separators (like `number_format`)
              $reg="#\\d{1,3}(?=(\\d{3})+(?:[.|$]))#";
              $str="1234567891238.5646656567";
              $res=preg_replace_callback($reg,
                      function($matches){
                      return ($matches[0].',');
                      },$str);
      example: negative lookahead — content inside tags that are **not** `<p>`
              $reg='#<(?!p)([^>\s]+)\s*(?:[^>]+)?>(.*?)</\1>#';
              $str="<p>sdfd</p><div>dddiv</div>dom<img src='aaa'/><a href='ssss'>some</a>other";
              $res=preg_match_all($reg,$str,$m);
    

    • (?#comment) — inline comment for readability
  • Back-references

    • \1, \2, … — repeat what an earlier captured group matched
    • \k<name> or (?P=name) — named back-reference

      example: quoted string where the opener and closer must match
              $reg="#(\"|').*?\\1#";
              //$reg="#(?P<quote>\"|').*?(?P=quote)#";
              $str="\"this is a 'string'\"";
              preg_match($reg,$str,$m);
    
  • Lazy quantifiers

    • *? — repeat as few times as possible

      example: without `?`, `.*` swallows up to the **last** `[/url]`
              $reg="#\\[url\\](.*?)\\[\\/url\\]#";
              $str="[url]1.png[/url][url]2.png[/url][url]3.png[/url]";
              $res=preg_replace($reg,"<img src='$1'/>",$str);
    
  • Case sensitivity

    • Ignore case globally: #...#i
    • Local: (?i)c — case-insensitive from the next character onward
  • Multiline

    • #...#m — ^ and $ match line starts/ends; $ normally means end of the whole string without m
  • Dotall (single-line)

    • #...#s — . matches newlines too (handy for multi-line blobs)
  • Lazy mode (PCRE)

    • #...#U — ungreedy quantifiers (similar effect to *?, +?, etc.)
  • Dollar and newline

    • #...#D — when $ is used, it must not match before \n
  • UTF-8 mode

    • #...#u — treat pattern and subject as UTF-8

      example: all-CJK string check
              $str="php百度";
              $reg='#^[\x{4e00}-\x{9fa5}]+$#u';
              if(preg_match($reg,$str,$m)){
                  echo 'all Chinese';
              }else{
                  echo 'not all Chinese';
              }
    

Tuning patterns

  • Prefer character classes over alternation: [a-c] beats (a|b|c) for speed
  • When alternates share a prefix, put the more specific branch first (e.g. 3- vs 4-digit postal codes)
  • Greedy quantifiers backtrack: \w*(\d+) on copy2003y can yield 3 because \w* eats the string first; use \w*? if you need the digits
  • Use . only when the character set is unknown; use {n} when counts are known; prefer lazy quantifiers when greed hurts
  • Use () sparingly; prefer (?:...) when you do not need captures
  • Anchor when you can: ^, $, and keep anchors outside groups when possible
  • Split huge patterns into smaller steps
  • Reach for PHP builtins before regex when they fit
    • Validation: filter_var('admin@qq.com', FILTER_VALIDATE_EMAIL)
    • PHP source: tokenizer_* instead of hand-rolled lexers
Questions? Leave a comment below or email: newbvirgil@gmail.com