Replace all occurences of char inside quotes on PHP

前端 未结 4 1197
我在风中等你
我在风中等你 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:51

    You can use preg_replace_callback for this;

    // outputs: hi \(text here\) and \(other text\) come (again)
    print preg_replace_callback('~"(.*?)"~', function($m) {
        return '"'. preg_replace('~([\(\)])~', '\\\$1', $m[1]) .'"';
    }, '"hi (text here) and (other text)" come (again)');
    

    What about already escaped strings;

    // outputs: hi \(text here\) and \(other text\) come (again)
    print preg_replace_callback('~"(.*?)"~', function($m) {
        return '"'. preg_replace('~(?:\\\?)([\(\)])~', '\\\$1', $m[1]) .'"';
    }, '"hi \(text here\) and (other text)" come (again)');
    

提交回复
热议问题