preg_match / preg_match_all
最后更新于:2022-04-02 02:29:28
[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('/(?\w+): (?\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.";
}
```
';