1

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?

Avatar
  • 14,622
  • 9
  • 119
  • 198

2 Answers2

1

You can search using this regex:

\$\$((?:(?!\$\$).)*)\$\$

and replace using:

\\($1\\)

RegEx Demo

Lookahead expression (?:(?!\$\$).) matches any character that is not a $$

Code:

$re = '/\$\$((?:(?!\$\$).)*)\$\$/';
$str = '$$ f\'(x) = 12x^2 + 4x $$  $$ f\'(x) = 12x+2x-12 $$  $$ f\'(x) = 12x^3 +4x^2 $$';
$subst = '\\\\($1\\\\)';

$result = preg_replace($re, $subst, $str);

As @Wiktor suggested below a simple non-greedy regex pattern will also work here:

\$\$(.*?)\$\$
anubhava
  • 761,203
  • 64
  • 569
  • 643
0

Regex: \${2}([^$]+)\${2} or \${2}(.+?)\${2} Substitution: ($1)

Details:

  • {n} Matches exactly n times
  • [^] Match a single character not present in the list
  • + Matches between one and unlimited times

PHP code:

$string = "$$ f'(x) = 12x^2 + 4x $$  $$ f'(x) = 12x+2x-12 $$  $$ f'(x) = 12x^3 +4x^2 $$";

$string = preg_replace('~\${2}([^$]+)\${2}~', '($1)', $string);
print_r($string);

Output:

( f'(x) = 12x^2 + 4x )  ( f'(x) = 12x+2x-12 )  ( f'(x) = 12x^3 +4x^2 )
Srdjan M.
  • 3,310
  • 3
  • 13
  • 34