ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
[TOC] ## 比较 preg_math与preg_match_all ``` preg_match_all("|(ab)c|", "abc abc abc", $out, PREG_PATTERN_ORDER); var_export($out); //array ( // 0 => // array ( // 0 => 'abc', // 1 => 'abc', // 2 => 'abc', // ), // 1 => // array ( // 0 => 'ab', // 1 => 'ab', // 2 => 'ab', // ), //) echo PHP_EOL; preg_match("|(ab)c|", "abc abc abc", $out); var_export($out); //array ( // 0 => 'abc', // 1 => 'ab', //) ``` ## 给匹配的值命名 ``` $str = 'foobar: 2008'; preg_match('/(?<name>\w+): (?<digit>\d+)/', $str, $matches); /** Array( [0] => foobar: 2008 [name] => foobar [1] => foobar [digit] => 2008 [2] => 2008 ) */ print_r($matches); ``` ## 是否符合正则 ``` if (preg_match("/php/i", "PHP is the web scripting language of choice.", $matches)) { print "A match was found:" . $matches[0]; } else { print "A match was not found."; } ```