$str = 'foobar: 2008newbeee: 2019';
preg_match('/(\w+): (\d+)/', $str, $matches1);
print_r($matches1);
/*
Array
(
[0] => foobar: 2008
[1] => foobar
[2] => 2008
)
*/
preg_match_all('/(\w+): (\d+)/', $str, $matches2);
print_r($matches2);
/*
Array
(
[0] => Array
(
[0] => foobar: 2008
[1] => newbeee: 2019
)
[1] => Array
(
[0] => foobar
[1] => newbeee
)
[2] => Array
(
[0] => 2008
[1] => 2019
)
)
*/
// 获取两个字符串中间字符串,preg_match和preg_match_all函数的默认模式是贪婪模式
$s = '222beginaaaaaendbbbbbend33333333';
$pattern = '/begin(.*?)end/'; // 非贪婪模式获取第一个
preg_match($pattern, $s, $matches);
print_r($matches[1]); // aaaaa
$pattern = '/begin(.*)end/'; // 贪婪模式获取越多越好
preg_match($pattern, $s, $matches);
print_r($matches[1]); // aaaaaendbbbbb
preg_match 与 preg_match_all
于 2019-07-10 09:54:56 首次发布