Home > Software engineering >  What Is The Regex To Replace This Specific html code With That Particular Code?
What Is The Regex To Replace This Specific html code With That Particular Code?

Time:04-07

I have some html code in a $_SESSION. One of the tags are:

</form>

Now, I want to replace that tag with:

</fieldset><fieldset>

How to achieve this ?

Following not working:

str_replace('</form>','</fieldset><fieldset>',$_SESSION['html_form_builder']);

I believe I will have to use preg_replace() instead. Will not str_replace() work if I try replacing symbols other than alpha-numerical chars ?

And, don't close this thread saying other threads exist teaching how to replace html code with preg_replace() because those threads' regex codes are no use to me as I am weak on regex. I actually need that specific regex to achieve my purpose.

CodePudding user response:

The regex would be something like

preg_replace('</form>', '</fieldset><fieldset>', $_SESSION['html_form_builder']);

But when i run that code i get an extra ">" which only disappears if i write

preg_replace('</form>', '/fieldset><fieldset', $_SESSION['html_form_builder']);

So the fieldset tags don't have the starting and ending <>

This is because the <> tags are used as delimiters in the str_replace and preg_replace functions. So str_replace would also work if you did:

str_replace('/form','/fieldset><fieldset', $_SESSION['html_form_builder']);
  • Related