PHP Regular Expressions (regexp/PCRE) String matching with regular expressions

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

preg_match checks whether a string matches the regular expression.

$string = 'This is a string which contains numbers: 12345';

$isMatched = preg_match('%^[a-zA-Z]+: [0-9]+$%', $string);
var_dump($isMatched); // bool(true)

If you pass in a third parameter, it will be populated with the matching data of the regular expression:

preg_match('%^([a-zA-Z]+): ([0-9]+)$%', 'This is a string which contains numbers: 12345', $matches);
// $matches now contains results of the regular expression matches in an array.
echo json_encode($matches); // ["numbers: 12345", "numbers", "12345"]

$matches contains an array of the whole match then substrings in the regular expression bounded by parentheses, in the order of open parenthesis's offset. That means, if you have /z(a(b))/ as the regular expression, index 0 contains the whole substring zab, index 1 contains the substring bounded by the outer parentheses ab and index 2 contains the inner parentheses b.



Got any PHP Question?