Replace all occurences of char inside quotes on PHP

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

    Here's how you can do it with the preg_replace_callback() function.

    $str = '"hi (text here) and (other text)" come (again)';
    $escaped = preg_replace_callback('~(["\']).*?\1~','normalizeParens',$str);
    // my original suggestion was '~(?<=").*?(?=")~' and I had to change it
    // due to your 2nd edit in your question. But there's still a chance that
    // both single and double quotes might exist in your string.
    
    function normalizeParens($m) {
        return preg_replace('~(?

提交回复
热议问题