![](/img/trans.png)
[英]PHP regex check if contains a specific word but doesn't contain another
[英]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>
我想搶購所有出現“咖啡”或“咖啡黑”的產品。
我嘗試使用以下代碼:
preg_match_all('/<product>(.*?)(black coffee|black-coffee)(.*?)<\/product>/is', $string, $result);
但是該代碼合並了數組中的兩個產品。 如您所知,我對regex一點都不熟悉。
您需要使用否定的超前斷言而不是.*?
因為.*?
還將匹配<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.