问题
So let's assume I have a text like this:
This is a great test! We're testing something awesome. Click here to <a href="whatever">test it!</a>.
I want to add some color to the word "test", but not if it's in an a tag. I've tried doing this:
/(?<!href="(.*?)">)test/
But it doesn't work. It works like this:
/(?<!href="whatever">)test/
But of course I have many links, so this isn't an option.
The whole code would be something like this:
$replacement = preg_replace('/(?<!href="SOLUTION HERE">)test/','<span style="color: #FF0000;">test</span>',$replacement);
Expected result:
This is a great <span style="color: #FF0000;">test</span>! We're <span style="color: #FF0000;">test</span>ing something awesome. Click here to <a href="whatever">test it!</a>.
回答1:
The quick, less reliable way to interact with html strings is with regex. DomDocument (or similar) is specially designed to parse html and is far more trustworthy. I'll post the regex way, and if I can manage it, I'll add a DomDocument way.
(*SKIP)(*FAIL)
allows you to match/consume and disqualify substrings then after the pipe you write the pattern for the substring that you actually want to replace.
Pattern: ~(?:<[^>]*>.*?</[^>]*>(*SKIP)(*FAIL))|\btest\b~s
Replace: <span style="color: #FF0000;">\0</span>
Pattern Demo
Code: (Demo)
$string="This is a great test! We're testing something awesome. Click here to <a href=\"whatever\">test it!</a>.";
$pattern='~(?:<[^>]*>.*?</[^>]*>(*SKIP)(*FAIL))|\btest\b~s';
$replace='<span style="color: #FF0000;">\0</span>';
echo preg_replace($pattern,$replace,$string);
Output:
This is a great <span style="color: #FF0000;">test</span>! We're testing something awesome. Click here to <a href="whatever">test it!</a>.
来源:https://stackoverflow.com/questions/47846415/regex-how-not-to-replace-specific-word-in-any-html-tag