Home/Guides/PHP preg_match Examples

PHP Regex Guides

PHP preg_match Examples

Simple preg_match and preg_match_all examples for extracting values with PHP regular expressions.

PHP preg_match() tests a string against a PCRE regular expression and can return captured groups.

Code examples

if (preg_match('/user_(\d+)/', 'user_42', $matches)) {
    echo $matches[1];
}

Find every match:

preg_match_all('/user_(\d+)/', 'user_42 user_99', $matches);

Common errors

Escape delimiters inside patterns, and remember that advanced PCRE features may not behave like JavaScript regex.

Try the PHP Regex Tester.

FAQ

When should I use preg_match_all?

Use preg_match_all when you need every match, not only the first one.

What does $matches contain?

It contains the full match and any captured groups.

Related tools