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?

411

Answer

Solution:

Here, we might want to capturehello andtest, then assemble what we like to have using apreg_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

People are also looking for solutions to the problem: javascript - How to send verification email with laravel's built in verification system with Gmail

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.