I have tried a couple of solutions regarding "replace second occurence in a string" (like here) but could not get the solution for my problem.
String example:
$string = "$$ f'(x) = 12x^2 + 4x $$ $$ f'(x) = 12x+2x-12 $$ $$ f'(x) = 12x^3 +4x^2 $$";
Goal:
$string = "\( f'(x) = 12x^2 + 4x \) \( f'(x) = 12x+2x-12 \) \( f'(x) = 12x^3 +4x^2 \)";
I found this gist snippet:
function str_replace_n($search, $replace, $subject, $occurrence)
{
$search = preg_quote($search);
return preg_replace("/^((?:(?:.*?$search){".--$occurrence."}.*?))$search/", "$1$replace", $subject);
}
And tried to carefully call it on the second instance by:
$string = str_replace_n('$$', '\)', $string, 2);
So that I can then go over the remaining $$
and replace them by \(
.
However, the function does nothing when I call it like that.
I thought it is an escape issue since $$
are rexeg operators, but even escaping them did not change the outcome (the preg_quote in the function should do the magic, I assume): $string = str_replace_n('\$\$', '\\)', $string, 2);
- nope …
What am I doing wrong?