0

So I have a string that looks like this <span>hey</span>/<span>bye</span>/<span>why</span>/. How would I use preg_replace to substitute all the non-HTML-tag /s with :: ?

Anas
  • 5,406
  • 5
  • 40
  • 69
bigpotato
  • 24,574
  • 50
  • 160
  • 313

1 Answers1

0

I would consider using negative lookbehind for this:

$pattern = '#(?<!<)/#';
$replacement = '::';
$result = preg_replace($pattern, $replacement, $input);

The gist of this is that it will only replace / where the preceding character is not <

Of course you might need to go a step further and make sure it doesn't have a following character of >, such as would be the case with self-closing tags. In that case, you could add a negative lookahead as well such that the pattern becomes:

$pattern = '#(?<!<)/(?!>)#';
Mike Brant
  • 68,891
  • 9
  • 93
  • 99