0

I tried:

echo preg_replace('<!--hello//-->','','<p>This is some text<!--hello//-->This is some more text</p>');

Trying to return

<p>This is some textThis is some more text</p>

But instead I got

<p>This is some text<>This is some more text</p>

Why do the brackets remain in the string?

Thanks for the help!

Edit: This question is not looking for the right regex to use...it's moreso why the function preg_replace is behaving weirdly.

Nick Manning
  • 2,828
  • 1
  • 29
  • 50
  • 1
    You need to add regex delimiters, `'~~'`. Or just use `str_replace` if you plan to remove a fixed substring. See https://ideone.com/OlAXUY. – Wiktor Stribiżew Jan 08 '18 at 14:41
  • Thanks @WiktorStribiżew! What is the purpose of those delimiters? – Nick Manning Jan 08 '18 at 14:47
  • Regex delimiters show the boundaries between the pattern and the modifiers (flags, or options). – Wiktor Stribiżew Jan 08 '18 at 14:48
  • 1
    In your case, the problem is that leading/trailing `<` and `>` are parsed as paired regex delimiters. Thus, you need to use more common ones, `/` or `~`, in addition to your *pattern*. – Wiktor Stribiżew Jan 08 '18 at 14:50
  • Ahhhh now I understand! I didn't realize that `<` and `>` were being treated as delimiters – Nick Manning Jan 08 '18 at 14:53
  • Like @WiktorStribiżew said. You'll need boundaries: `/ regex / flags` or `~ regex ~ flags`. Next, regex has certain [special characters](http://www.fon.hum.uva.nl/praat/manual/Regular_expressions_1__Special_characters.html) which need to be escaped if used as literal characters. Something to keep in mind :) – icecub Jan 08 '18 at 14:53
  • Yes, I was amazed that none of these characters needed to be escaped based on the list I found. Turns out the list didn't include delimiters. – Nick Manning Jan 08 '18 at 14:54
  • @NickManning: as an aside, regex is absolutely not the way to edit html, use DOMDocument and DOMXPath to do that. This way you can avoid false positive, for example: `` – Casimir et Hippolyte Jan 08 '18 at 16:17

0 Answers0