In a string containing some html I want to find and replace every occurrence of a <h1-6>
tag, including anything that follows it, up until another <h1-6>
tag or until the end of the html string.
My pattern: <h\d.+?(?=<h\d)
With /gs flags this pattern works fine on this online testing tool.
However, on server side test I am only able to make my pattern match the first occurrence, while the rest are being ignored.
PHP Manual states:
Searches subject for matches to pattern and replaces them with replacement.
Another post answer mentions:
preg_replace() will perform global replacements by default
According to the above, my server side pattern should work if changed to /<h\d.+?(?=<h\d)/s
, but for some reason it still only replaces the first occurrence.
Full code:
$html = get_html_string();
$pattern = '/<h\d.+?(?=<h\d)/s';
$replace = '<div>$0</div>';
$html = preg_replace($pattern, $replace, $html);
return $html;
Update:
Looks like my html example somehow differs from actual html on the website. Because of this I made sure to copy the string that i want to manipulate directly in to the online tester tool. Now it is apparent that matching works but the actual problem was that last match is not included. See this updated test.
Thanks to Nick for the answer and everyone else for chiming in.