php 正则表达式提取匹配标签包含特定词的地方

php regex extract matches where tag contain a specific word

我有以下字符串:

<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>

我想抓取出现 "coffee" 或 "coffee black" 的所有产品。

我尝试使用以下代码:

preg_match_all('/<product>(.*?)(black coffee|black-coffee)(.*?)<\/product>/is', $string, $result);

但是该代码合并了数组中的两个产品。如您所知,我一点也不熟悉正则表达式。

您需要使用否定前瞻断言而不是 .*?,因为 .*? 也将匹配 <product></product> 标签。

<product>((?:(?!<\/?product).)*?)(black coffee|black-coffee)((?:(?!<\/?product).)*?)<\/product>

DEMO

$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])