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,622
  • 5
  • 39
  • 71
bigpotato
  • 26,262
  • 56
  • 178
  • 334

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
  • 70,514
  • 10
  • 99
  • 103