How do I adjust my code below to replace the second » character using preg_replace?
$out = 'Home » Food » Fruit';
$out = preg_replace('/»/', 'Category:', $out, 1);
Thanks in advance!
To only remove the second occurrence of a string, you need to match the first one, and then match and capture all text up to the second one, and then replace using a backreference.
Use
$out = 'Home » Food » Fruit';
$out = preg_replace('/(»[^»]*)»/', '$1Category:', $out, 1);
echo $out;
See the PHP demo. The last $limit argument will have preg_replace only replace the first match.
Details:
(»[^»]*) - Capturing group #1 matching
» - a literal »[^»]* - 0+ occurrences (due to * quantifier) of any chars other than »» - a literal »See the regex demo.
A variation that is only supported in Boost/PCRE (and latest versions of Onigmo) and will also work for you:
/»[^»]*\K»/
See another regex demo. \K will discard all the text matched so far in the current iteration. so you will only have the closing chevron in the match to be replaced with your replacement string.