I want to str_replace
in a function.
str_replace(array('(', ')', array('"', '\'')), array('\(', '\)', '["|\']'), 'hello("test")');
hello\(["|']test["|']\)
This would work, but not very useful:
str_replace(array('"', '\''), '["|\']', str_replace(array('(', ')'), array('\(', '\)'), 'hello("test")'));
How do I solve this problem?
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;
hello\(["|']test["|'"]\)
You can modify/change your expressions in regex101.com.
You can also visualize your expressions in jex.im: