0

I have to replace 'page1' in some code with '<a href="/page1">page1</a>'

However, I only want to do so if it is not already a link. How can I do the same using php regular expressions.

  • Use case 1 - page1 -> should change to <a href="/page1">page1</a>
  • Use case 2 - <a href="/page1">page1</a> -> nothing should be changed
stema
  • 90,351
  • 20
  • 107
  • 135

1 Answers1

1

If you know the exact link text in advance then you can just check for the existence of quotes or angled brackets before and after it. Are you sure this is the question you should be asking?

For the exact string 'page1':

preg_replace('#(^|[^"\'>])\s*(page1)\s*($|[^"\'<])#is', '<a href="$2">$2</a>', $s);

This is a bad solution though really. You should use a HTML parser because regex is never reliable for things like this. It could break under certain conditions.

diolemo
  • 2,621
  • 2
  • 21
  • 28