Replace all occurences of char inside quotes on PHP

前端 未结 4 1199
我在风中等你
我在风中等你 2021-01-28 02:36

How could I convert something like this:

\"hi (text here) and (other text)\" come (again)

To this:

\"hi \\(text here\\) and \\(         


        
4条回答
  •  甜味超标
    2021-01-28 02:47

    Given the string

    $str = '"hi (text here) and (other text)" come (again) "maybe (to)morrow?" (yes)';
    

    Iterative method

     for ($i=$q=0,$res='' ; $i

    But if you're a fan of recursion

     function rec($i, $n, $q) {
       global $str;
       if ($i >= $n) return '';
       $c = $str[$i];
       if ($c == '"') $q ^= 1;
       elseif ($q && ($c == '(' || $c == ')')) $c = '\\' . $c;
       return $c . rec($i+1, $n, $q);
     }
    
     echo rec(0, strlen($str), 0) . "\n";
    

    Result:

    "hi \(text here\) and \(other text\)" come (again) "maybe \(to\)morrow?" (yes)
    

提交回复
热议问题