替换PHP中所有出现在引号内的char [英] Replace all occurences of char inside quotes on PHP

查看:54
本文介绍了替换PHP中所有出现在引号内的char的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我该如何转换这样的内容:

How could I convert something like this:

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

到此:

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

基本上,我想仅转义引号内的括号。

Basically, I want to escape "only" the parentheses that are inside quotes.

编辑

我是Regex的新用户,因此,我尝试了以下操作:

I'm to new in Regex and so, I tried this:

$params = preg_replace('/(\'[^\(]*)[\(]+/', '$1\\\($2', $string);

但这只会逃避第一次出现(。

But this will just escape the first occurrence of (.

编辑2

也许我应该提一下,我的字符串可能已经转义了这些括号,在这种情况下,我不想

Maybe I should mention that my string could have these parentheses already escaped and, in this case, I don't want to escaped them again.

顺便说一句,我需要它同时适用于双引号和单引号,但是我认为只要有一个可行的例子,我就可以做到这一点。其中之一。

By the way, I need it working for both double and single quotes but I think that I can do that as long as I have a working example for one of them.

推荐答案

对于单引号和双引号,都应该这样做:

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('`(?<!\\\)[()]`', '\\\$0', $matches[0]);
}, $str);

echo $str;

输出

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

它用于PHP> = 5.3。如果您的版本较低(> = 5),则必须用单独的函数替换回调函数中的匿名函数。

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.

这篇关于替换PHP中所有出现在引号内的char的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆