Search code examples
phpregexstr-replaceregex-groupregex-greedy

RegEx for capturing and replacing a string with quotes


I want to str_replace in a function.

Attempt

str_replace(array('(', ')', array('"', '\'')), array('\(', '\)', '["|\']'), 'hello("test")');

Desired output:

hello\(["|']test["|']\)

This would work, but not very useful:

str_replace(array('"', '\''), '["|\']', str_replace(array('(', ')'), array('\(', '\)'), 'hello("test")'));

How do I solve this problem?


Solution

  • Here, we might want to capture hello and test, then assemble what we like to have using a preg_replace:

    $re = '/(.*)\("(.+)"\)/m';
    $str = 'hello("test")';
    $subst = "$1\([\"|']$2[\"|'\"]\)";
    
    $result = preg_replace($re, $subst, $str);
    
    echo $result;
    

    Output

    hello\(["|']test["|'"]\)
    

    RegEx

    enter image description here

    RegEx

    You can modify/change your expressions in regex101.com.

    RegEx Circuit

    You can also visualize your expressions in jex.im:

    enter image description here