199 of 410 menu

The preg_match Function

The preg_match function searches a string for matches with a regular expression. The first parameter accepts the regular expression pattern, the second - the string to search, the third (optional) - an array to save found matches, the fourth (optional) - flags, the fifth (optional) - the offset of the start of the search.

Syntax

preg_match(pattern, subject, [matches], [flags], [offset]);

Flags

Flag Constant Description
PREG_PATTERN_ORDER 1 Results are sorted by patterns (default)
PREG_SET_ORDER 2 Results are sorted by match sets
PREG_OFFSET_CAPTURE 256 Returns the position of the match in the string
PREG_UNMATCHED_AS_NULL 512 Unmatched subpatterns are returned as NULL

Example

Let's check if the string contains digits:

<?php $res = preg_match('/\d+/', 'abc123'); echo $res; ?>

Code execution result:

1

Example

Let's extract all digits from the string into an array:

<?php preg_match('/\d+/', 'abc123', $matches); var_dump($matches); ?>

Code execution result:

[0 => '123']

Example

Using named groups in a regular expression:

<?php preg_match('/(?P<name>\w+)\s+(?P<age>\d+)/', 'John 25', $matches); var_dump($matches); ?>

Code execution result:

[ 0 => 'John 25', 'name' => 'John', 1 => 'John', 'age' => '25', 2 => '25' ]

Example

Using the PREG_OFFSET_CAPTURE flag to get the match position:

<?php preg_match('/\d+/', 'abc123', $matches, PREG_OFFSET_CAPTURE); var_dump($matches); ?>

Code execution result:

[ 0 => [ 0 => '123', 1 => 3 ] ]

Example

Search with an offset specified:

<?php preg_match('/\d+/', '123abc456', $matches, 0, 3); var_dump($matches); ?>

Code execution result:

[0 => '456']

Example

Checking the validity of an email address:

<?php $email = 'test@example.com'; $res = preg_match('/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/', $email); echo $res ? 'Valid' : 'Invalid'; ?>

Code execution result:

'Valid'

See Also

  • the preg_match_all function,
    which finds all matches in a string
  • the preg_replace function,
    which performs replacement by regular expression
byenru