介绍
首先,我的一般问题是我想用字符串替换字符串中的问号,但前提是它们没有被引用。所以我在 SO (链接)上找到了一个类似的答案,并开始测试代码。不幸的是,当然,代码没有考虑转义引号。
例如:$string = 'hello="is it me your are looking for\\"?" AND test=?';
我已经从该问题的答案中改编了一个正则表达式和代码:如何替换双引号和单引号之外的单词,为了便于阅读我的问题,在此复制:
<?php
function str_replace_outside_quotes($replace,$with,$string){
$result = "";
$outside = preg_split('/("[^"]*"|\'[^\']*\')/',$string,-1,PREG_SPLIT_DELIM_CAPTURE);
while ($outside)
$result .= str_replace($replace,$with,array_shift($outside)).array_shift($outside);
return $result;
}
?>
实际问题
所以我试图调整模式以允许它匹配任何不是引号"
和转义的引号\"
:
<?php
$pattern = '/("(\\"|[^"])*"' . '|' . "'[^']*')/";
// when parsed/echoed by PHP the pattern evaluates to
// /("(\"|[^"])*"|'[^']*')/
?>
但这并不像我希望的那样工作。
我的测试字符串是:hello="is it me your are looking for\"?" AND test=?
我得到以下比赛:
array
0 => string 'hello=' (length=6)
1 => string '"is it me your are looking for\"?"' (length=34)
2 => string '?' (length=1)
3 => string ' AND test=?' (length=11)
匹配索引二不应该存在。该问号应仅被视为匹配索引 1 的一部分,而不应单独重复。
一旦解决了这个相同的修复也应该更正单引号/撇号的主要交替的另一侧'
。
在由完整函数解析后,它应该输出:
echo str_replace_outside_quotes('?', '%s', 'hello="is it me your are looking for\\"?" AND test=?');
// hello="is it me your are looking for\"?" AND test=%s
我希望这是有道理的,并且我已经提供了足够的信息来回答这个问题。如果没有,我会很乐意提供您需要的任何东西。
调试代码
我当前(完整)的代码示例也在用于分叉的键盘上:
function str_replace_outside_quotes($replace, $with, $string){
$result = '';
var_dump($string);
$pattern = '/("(\\"|[^"])*"' . '|' . "'[^']*')/";
var_dump($pattern);
$outside = preg_split($pattern, $string, -1, PREG_SPLIT_DELIM_CAPTURE);
var_dump($outside);
while ($outside) {
$result .= str_replace($replace, $with, array_shift($outside)) . array_shift($outside);
}
return $result;
}
echo str_replace_outside_quotes('?', '%s', 'hello="is it me your are looking for\\"?" AND test=?');
样本输入和预期输出
In: hello="is it me your are looking for\\"?" AND test=? AND hello='is it me your are looking for\\'?' AND test=? hello="is it me your are looking for\\"?" AND test=?' AND hello='is it me your are looking for\\'?' AND test=?
Out: hello="is it me your are looking for\\"?" AND test=%s AND hello='is it me your are looking for\\'?' AND test=%s hello="is it me your are looking for\\"?" AND test=%s AND hello='is it me your are looking for\\'?' AND test=%s
In: my_var = ? AND var_test = "phoned?" AND story = 'he said \'where is it?!?\''
Out: my_var = %s AND var_test = "phoned?" AND story = 'he said \'where is it?!?\''