php - Replace all matches within the tag
275
There is the following line:
$str = '<div class="hello"> Hello world < hello world?! </div>';
Need to find all the matches within the tag, while avoiding a match attribute values. Try something like:
$pattern = '/(.*)(hello)(.*)(?=<\/)/ui';
$replacement = '$1<span class="page_speed_748935785">$2</span>$3';
but yet there is only one "hello". What to do?
Answer
Solution:
(*SKIP)(*F) Syntax in Perl and PCRE (PHP, Delphi, R...)
With all the disclaimers about using regex to parse html, we can do this with a surprisingly simple regex:
Sample PHP Code:
In the regex demo, see the substitutions at the bottom.
Explanation
This problem is a classic case of the technique explained in this question to "regex-match a pattern, excluding..."
The left side of the alternation
matches complete
|<tags>
then deliberately fails, after which the engine skips to the next position in the string. The right side captureshello
(case-insensitive to Group 1, and we know they are the right ones because they were not matched by the expression on the left.Reference
Answer
Solution:
Wrapping text matches into another element is a pretty basic operation, though the code is somewhat tricky: