我怎么能转换是这样的:
"hi (text here) and (other text)" come (again)
为此:
"hi \(text here\) and \(other text\)" come (again)
基本上,我想逃离“只”是引号里的括号。
编辑
我对新的正则表达式,因此,我尝试这样做:
$params = preg_replace('/(\'[^\(]*)[\(]+/', '$1\\\($2', $string);
但是,这只会逃避的第一次出现(。
编辑2
也许我应该提及我的字符串可以有这些括号已经逃脱了,在这种情况下,我不希望他们再次逃脱做。
顺便说一句,我需要工作两个双人和单引号,但我想我能做到这一点,只要我对他们的一个工作示例。
这应该对单引号和双引号做到这一点:
$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)你有一个单独的函数来代替回调的匿名函数。
您可以使用preg_replace_callback此;
// outputs: hi \(text here\) and \(other text\) come (again)
print preg_replace_callback('~"(.*?)"~', function($m) {
return '"'. preg_replace('~([\(\)])~', '\\\$1', $m[1]) .'"';
}, '"hi (text here) and (other text)" come (again)');
什么已逃走串;
// outputs: hi \(text here\) and \(other text\) come (again)
print preg_replace_callback('~"(.*?)"~', function($m) {
return '"'. preg_replace('~(?:\\\?)([\(\)])~', '\\\$1', $m[1]) .'"';
}, '"hi \(text here\) and (other text)" come (again)');
鉴于串
$str = '"hi (text here) and (other text)" come (again) "maybe (to)morrow?" (yes)';
迭代方法
for ($i=$q=0,$res='' ; $i<strlen($str) ; $i++) {
if ($str[$i] == '"') $q ^= 1;
elseif ($q && ($str[$i]=='(' || $str[$i]==')')) $res .= '\\';
$res .= $str[$i];
}
echo "$res\n";
但如果你是递归的粉丝
function rec($i, $n, $q) {
global $str;
if ($i >= $n) return '';
$c = $str[$i];
if ($c == '"') $q ^= 1;
elseif ($q && ($c == '(' || $c == ')')) $c = '\\' . $c;
return $c . rec($i+1, $n, $q);
}
echo rec(0, strlen($str), 0) . "\n";
结果:
"hi \(text here\) and \(other text\)" come (again) "maybe \(to\)morrow?" (yes)
这里是你如何可以用做preg_replace_callback()
函数。
$str = '"hi (text here) and (other text)" come (again)';
$escaped = preg_replace_callback('~(["\']).*?\1~','normalizeParens',$str);
// my original suggestion was '~(?<=").*?(?=")~' and I had to change it
// due to your 2nd edit in your question. But there's still a chance that
// both single and double quotes might exist in your string.
function normalizeParens($m) {
return preg_replace('~(?<!\\\)[()]~','\\\$0',$m[0]);
// replace parens without preceding backshashes
}
var_dump($str);
var_dump($escaped);