What is the usage of php preg_match?

The preg_match function is used to match regular expressions in a string.

Grammar: the rules governing the structure of a language.

preg_match($pattern, $subject, $matches)

parameters:

  1. $pattern: regular expression pattern.
  2. $subject: the string that needs to be matched.
  3. $matches: an array used to store the results of a match.

Return value:

  1. If a match is successful, return 1 (true); if a match fails, return 0 (false).

I am not in the mood to go out tonight.

I don’t feel like going out tonight.

$pattern = '/\d+/';  // 匹配连续的数字
$subject = 'abc123def456';
$matches = array();

if (preg_match($pattern, $subject, $matches)) {
    echo "匹配成功!";
    echo "匹配到的数字为:" . $matches[0];
} else {
    echo "匹配失败!";
}

output:

匹配成功!
匹配到的数字为:123

In the example above, the regular expression pattern /\d+/ matches consecutive numbers. You can use the preg_match function to store the matching result in the $matches array, with the matched number being $matches[0].

bannerAds