4

How to replace string using overlapping regular expressions?

Hello! Im trying to add html tags into string. Im using function preg_replace(), but when my patterns in array are overlaped the preg_replace doesn't work.

$string = 'abc';
$patterns[0] = '/a/';
$patterns[1] = '/abc/';
$replacements[0] = '<b>$0</b>';
$replacements[1] = '<i>$0</i>';
echo preg_replace($patterns, $replacements, $string);

This produce the following output:

<b>a</b>bc

But i expected this output:

<b><i>a</b>bc</i>

It seems like preg_replace takes first pattern and replace it with first replacement and then search for second pattern but it search in modified string. I must use functions which support regular expressions.

6
  • 2
    You do realise that <b><i>a</b>bc</i> is invalid markup? You'd need <i><b>a</b>bc</i> to be valid! Commented Feb 27, 2015 at 14:43
  • Yes I do, thats not the problem Commented Feb 27, 2015 at 14:46
  • Well part of the problem is that regexp isn't the right tool for the job, DOM is the right tool Commented Feb 27, 2015 at 14:47
  • @vks that's not the solution, i get 1 or more regex, which may or may not define the same language Commented Feb 27, 2015 at 15:02
  • @MarkBaker could you explain how to use DOM tool for this? Commented Feb 27, 2015 at 15:02

1 Answer 1

2

It's because they don't run simultaneously, but in loop. And after first expression you end up with <b>a</b>bc so there is no more any abc for second expression to match.

It's simply as that. And that's good, because thanks to that you won't end with invalid markup. You will. Regex is serious problem with HTML or XML.

Use some DOM interpreter and library, like PHP's DOMDocument

Sign up to request clarification or add additional context in comments.

1 Comment

Could you explain how to use DOM library in PHP to this? I have never heard about it...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.