I want to replace the second h2 tag to h3 and I hope someone can help me with a replacement regex, or maybe a preg_split – I am not exactly sure.
For example, this:
<h2>My text one</h2>
<h2>My text two</h2>
text …
<h2>My text three</h2>
Should become this:
<h2>My text one</h2>
<h3>My text two</h3>
text …
<h2>My text three</h2>
I agree with the other commentaries, this should be done through a dom parser. But here is a working php solution nevertheless.
or
This should work just fine. Adding the $matches parameter to preg_replace will also keep track of the number of changes made.
Now, using a loop you may control which element needs to be replaced, however, the functions as written above will detect all occurences of h2.
Also, I’ve overly complicated the regexp for you to be able to swap out the number, to make a more useful function with it. Just using “/(h2)/i” will do the trick too.
So, your code should implement a loop in the correct manner to prevent replacing all of the tags and you should decide if the function is going to handle just h2 or if it should be more flexible.
As a final remark, str_replace is faster than preg_replace, so if this is the only edit you need to make, I would recommend str_replace.