在PHP中使用正则表达式捕获时如何忽略字符串中的单词?
问题描述:
Here is what my code looks like:
preg_replace("/(test)/i", "<strong>$1</strong>", $text);
And here is an example string:
"<a href="www.website.com/search/%23test">#test</a>"
I want to capture the second 'test' but not the first one in the URL.
以下是我的代码: p>
preg_replace( “/(test)/ i”,“&lt; strong&gt; $ 1&lt; / strong&gt;”,$ text);
code> pre>
这是一个示例字符串: p>
“&lt; a href =”www.website.com/search/%23test“&gt; #test&lt; / a&gt;”
code> pre >
我想捕获第二个“测试”,但不是第一个“测试”。 p>
div>
答
You can avoid matching something which is inside angular brackets (at least, if there are no literal angular brackets in the text) with a negative lookahead:
preg_replace("/test(?![^<>]*>)/i", "<strong>$0</strong>", $text);