php - RegEx for capturing and replacing a string with quotes
760
I want tostr_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?
Answer
Solution:
Here, we might want to capture
hello
andtest
, then assemble what we like to have using apreg_replace
:Output
RegEx
RegEx
You can modify/change your expressions in regex101.com.
RegEx Circuit
You can also visualize your expressions in jex.im: