我有一个字符串,其中我试图破解容易处理的数据。对于这个例子,我想要的是以及consensus数据。
$digits = '[\$]?[\d]{1,3}(?:[\.][\d]{1,2})?';
$price = '(?:' . $digits . '(?:[\-])?' . $digits . '[\s]?(?:million|billion)?)';
$str = 'revenue of $31-34 billion, versus the consensus of $29.3 billion';
preg_match_all('/(?:revenue|consensus)(?:.*)' . $price . '/U', $str, $matches[]);
print_r($matches);返回:
Array (
[0] => Array (
[0] => Array (
[0] => 'revenue of $31'
[1] => 'consensus of $29'
)
)
)我期待的是:
Array (
[0] => Array (
[0] => Array (
[0] => 'revenue of $31-34 billion'
[1] => 'consensus of $29.3 billion'
)
)
)当我省略U修饰符时:
Array (
[0] => Array (
[0] => Array (
[0] => 'revenue of $31-34 billion, versus the consensus of $29.3 billion'
)
)
)我不能在of中使用revenue of $31-34 billion作为一个明确的模式,数据可能/可能不使用它,因此我使用了(?:.*)。
发布于 2013-04-04 13:40:01
preg_match_all('/(?:revenue|consensus)(?:.*?)' . $price . '/', $str, $matches[]);
^ ^ 通过添加?,可以使一个特定的通配符不贪婪,就像在.*?中一样。去掉全局/U修饰符,将上面的通配符更改为不贪婪的通配符,让$digits和$price单独使用。
Array
(
[0] => Array
(
[0] => Array
(
[0] => revenue of $31-34 billion
[1] => consensus of $29.3 billion
)
)
)https://stackoverflow.com/questions/15812863
复制相似问题