[英]php regex extract matches where tag contain a specific word
I have the following string: 我有以下字符串:
<product><name>Tea</name><price>12</price></product>
<product><name>black coffee</name><price>23</price></product>
<product><name>cheap black-coffee</name><price>44</price></product>
I would like to grab all products where "coffee" or "coffee black" occurs. 我想抢购所有出现“咖啡”或“咖啡黑”的产品。
I tried with the following code: 我尝试使用以下代码:
preg_match_all('/<product>(.*?)(black coffee|black-coffee)(.*?)<\/product>/is', $string, $result);
But that code merges two of the products in the array. 但是该代码合并了数组中的两个产品。 As you can tell, I am not at all familiar with regex.
如您所知,我对regex一点都不熟悉。
You need to use a negative lookahead assertion instead of .*?
您需要使用否定的超前断言而不是
.*?
because .*?
因为
.*?
will also match <product>
or </product>
tags. 还将匹配
<product>
或</product>
标签。
<product>((?:(?!<\/?product).)*?)(black coffee|black-coffee)((?:(?!<\/?product).)*?)<\/product>
$re = "/<product>(?:(?:(?!<\\/?product).)*?)(?:black coffee|black-coffee)(?:(?:(?!<\\/?product).)*?)<\\/product>/is";
$str = "<product><name>Tea</name><price>12</price></product>\n<product><name>black coffee</name><price>23</price></product>\n<product><name>cheap black-coffee</name><price>44</price></product>";
preg_match_all($re, $str, $matches);
print_r($matches[0])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.