Replace all occurences of char inside quotes on PHP

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

    This should do it for both single and double quotes:

    $str = '"hi \(text here)" and (other text) come \'(again)\'';
    
    $str = preg_replace_callback('`("|\').*?\1`', function ($matches) {
        return preg_replace('`(?

    output

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

    It is for PHP >= 5.3. If you have a lower version (>=5) you have to replace the anonymous function in the callback with a separate function.

提交回复
热议问题