首先,我的一般问题是我想在字符串中替换问号,但只有在不引用时才会这样。所以我在SO(link)上找到了类似的答案,并开始测试代码。不幸的是,当然,代码没有考虑转义引号。
例如:$string = 'hello="is it me your are looking for\\"?" AND test=?';
我已将that answer的正则表达式和代码改编为问题:How to replace words outside double and single quotes,为了便于阅读我的问题,此处转载于此处:
<?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)
匹配索引2不应该在那里。该问号应仅被视为匹配索引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
我希望这是有道理的,我已经提供了足够的信息来回答这个问题。如果没有,我会乐意提供你需要的任何东西。
我当前(完整)的代码示例为on codepad for forking as well:
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?!?\''
答案 0 :(得分:3)
以下测试过的脚本首先检查给定的字符串是否有效,仅由单引号,双引号和未引用的块组成。 $re_valid
正则表达式执行此验证任务。如果字符串有效,则使用preg_replace_callback()
和$re_parse
正则表达式一次解析一个字符串。回调函数使用preg_replace()
处理未加引号的块,并且不加改变地返回所有引用的块。逻辑中唯一棘手的部分是将$replace
和$with
参数值从main函数传递给回调函数。 (注意PHP程序代码使得这个变量从main函数传递到回调函数有点尴尬。)这是脚本:
<?php // test.php Rev:20121113_1500
function str_replace_outside_quotes($replace, $with, $string){
$re_valid = '/
# Validate string having embedded quoted substrings.
^ # Anchor to start of string.
(?: # Zero or more string chunks.
"[^"\\\\]*(?:\\\\.[^"\\\\]*)*" # Either a double quoted chunk,
| \'[^\'\\\\]*(?:\\\\.[^\'\\\\]*)*\' # or a single quoted chunk,
| [^\'"\\\\]+ # or an unquoted chunk (no escapes).
)* # Zero or more string chunks.
\z # Anchor to end of string.
/sx';
if (!preg_match($re_valid, $string)) // Exit if string is invalid.
exit("Error! String not valid.");
$re_parse = '/
# Match one chunk of a valid string having embedded quoted substrings.
( # Either $1: Quoted chunk.
"[^"\\\\]*(?:\\\\.[^"\\\\]*)*" # Either a double quoted chunk,
| \'[^\'\\\\]*(?:\\\\.[^\'\\\\]*)*\' # or a single quoted chunk.
) # End $1: Quoted chunk.
| ([^\'"\\\\]+) # or $2: an unquoted chunk (no escapes).
/sx';
_cb(null, $replace, $with); // Pass args to callback func.
return preg_replace_callback($re_parse, '_cb', $string);
}
function _cb($matches, $replace = null, $with = null) {
// Only set local static vars on first call.
static $_replace, $_with;
if (!isset($matches)) {
$_replace = $replace;
$_with = $with;
return; // First call is done.
}
// Return quoted string chunks (in group $1) unaltered.
if ($matches[1]) return $matches[1];
// Process only unquoted chunks (in group $2).
return preg_replace('/'. preg_quote($_replace, '/') .'/',
$_with, $matches[2]);
}
$data = file_get_contents('testdata.txt');
$output = str_replace_outside_quotes('?', '%s', $data);
file_put_contents('testdata_out.txt', $output);
?>
答案 1 :(得分:1)
此正则表达式匹配有效的引用字符串。这意味着它知道转义的报价。
^("[^\"\\]*(?:\\.[^\"\\]*)*(?![^\\]\\)")|('[^\'\\]*(?:\\.[^\'\\]*)*(?![^\\]\\)')$
准备好使用PHP:
$pattern = '/^((?:"([^"\\\\]*(?:\\\\.[^"\\\\]*)*(?![^\\\\]\\\\))")|(?:\'([^\'\\\\]*(?:\\\\.[^\'\\\\]*)*(?![^\\\\]\\\\))\'))$/';
改编为str_replace_outside_quotes()
:
$pattern = '/((?:"(?:[^"\\\\]*(?:\\\\.[^"\\\\]*)*(?![^\\\\]\\\\))")|(?:\'(?:[^\'\\\\]*(?:\\\\.[^\'\\\\]*)*(?![^\\\\]\\\\))\'))/';
答案 2 :(得分:1)
»代码已更新,以解决评论中带来的所有问题,现在工作正常«
输入$s
,短语字符串为$p
,替换变量为$v
,请按以下方式使用preg_replace:
$r = '/\G((?:(?:[^\x5C"\']|\x5C(?!["\'])|\x5C["\'])*?(?:\'(?:[^\x5C\']|\x5C(?!\')' .
'|\x5C\')*\')*(?:"(?:[^\x5C"]|\x5C(?!")|\x5C")*")*)*?)' . preg_quote($p) . '/';
$s = preg_match($r, $s) ? preg_replace($r, "$1" . $v, $s) : $s;
检查 this demo 。
注意:在正则表达式中,\x5C
代表\
个字符。
答案 3 :(得分:-1)
编辑,更改了答案。不适用于正则表达式(只有现在的正则表达式 - 我认为使用preg_replace而不是str_replace会更好,但你可以改变它)):
function replace_special($what, $with, $str) {
$res = '';
$currPos = 0;
$doWork = true;
while (true) {
$doWork = false; //pesimistic approach
$pos = get_quote_pos($str, $currPos, $quoteType);
if ($pos !== false) {
$posEnd = get_specific_quote_pos($str, $quoteType, $pos + 1);
if ($posEnd !== false) {
$doWork = $posEnd !== strlen($str) - 1; //do not break if not end of string reached
$res .= preg_replace($what, $with,
substr($str, $currPos, $pos - $currPos));
$res .= substr($str, $pos, $posEnd - $pos + 1);
$currPos = $posEnd + 1;
}
}
if (!$doWork) {
$res .= preg_replace($what, $with,
substr($str, $currPos, strlen($str) - $currPos + 1));
break;
}
}
return $res;
}
function get_quote_pos($str, $currPos, &$type) {
$pos1 = get_specific_quote_pos($str, '"', $currPos);
$pos2 = get_specific_quote_pos($str, "'", $currPos);
if ($pos1 !== false) {
if ($pos2 !== false && $pos1 > $pos2) {
$type = "'";
return $pos2;
}
$type = '"';
return $pos1;
}
else if ($pos2 !== false) {
$type = "'";
return $pos2;
}
return false;
}
function get_specific_quote_pos($str, $type, $currPos) {
$pos = $currPos - 1; //because $fromPos = $pos + 1 and initial $fromPos must be currPos
do {
$fromPos = $pos + 1;
$pos = strpos($str, $type, $fromPos);
}
//iterate again if quote is escaped!
while ($pos !== false && $pos > $currPos && $str[$pos-1] == '\\');
return $pos;
}
示例:
$str = 'hello ? ="is it me your are looking for\\"?" AND mist="???" WHERE test=? AND dzo=?';
echo replace_special('/\?/', '#', $str);
返回
你好#=“我是你在寻找\”?“和雾=”???“在哪里 test =#AND dzo =#
- 旧答案(我住在这里,因为它解决了一些问题,虽然不是完整的问题)
<?php
function str_replace_outside_quotes($replace, $with, $string){
$result = '';
var_dump($string);
$pattern = '/(?<!\\\\)"/';
$outside = preg_split($pattern, $string, -1, PREG_SPLIT_DELIM_CAPTURE);
var_dump($outside);
for ($i = 0; $i < count($outside); ++$i) {
$replaced = str_replace($replace, $with, $outside[$i]);
if ($i != 0 && $i != count($outside) - 1) { //first and last are not inside quote
$replaced = '"'.$replaced.'"';
}
$result .= $replaced;
}
return $result;
}
echo str_replace_outside_quotes('?', '%s', 'hello="is it me your are looking for\\"?" AND test=?');
答案 4 :(得分:-1)
正如@ridgerunner在关于该问题的评论中提到的还有另一种可能的正则表达式解决方案:
function str_replace_outside_quotes($replace, $with, $string){
$result = '';
$pattern = '/("[^"\\\\]*(?:\\\\.[^"\\\\]*)*")' // hunt down unescaped double quotes
. "|('[^'\\\\]*(?:\\\\.[^'\\\\]*)*')/s"; // or single quotes
$outside = array_filter(preg_split($pattern, $string, -1, PREG_SPLIT_DELIM_CAPTURE));
while ($outside) {
$result .= str_replace($replace, $with, array_shift($outside)) // outside quotes
. array_shift($outside); // inside quotes
}
return $result;
}
请注意使用array_filter
删除从正则表达式返回的一些匹配项,并打破此函数的交替性质。
没有正则表达式的方法,我很快就被淘汰了。它有效,但我确信可以做一些优化。
function str_replace_outside_quotes($replace, $with, $string){
$string = str_split($string);
$accumulation = '';
$current_unquoted_string = null;
$inside_quote = false;
$quotes = array("'", '"');
foreach($string as $char) {
if ($char == $inside_quote && "\\" != substr($accumulation, -1)) {
$inside_quote = false;
} else if(false === $inside_quote && in_array($char, $quotes)) {
$inside_quote = $char;
}
if(false === $inside_quote) {
$current_unquoted_string .= $char;
} else {
if(null !== $current_unquoted_string) {
$accumulation .= str_replace($replace, $with, $current_unquoted_string);
$current_unquoted_string = null;
}
$accumulation .= $char;
}
}
if(null !== $current_unquoted_string) {
$accumulation .= str_replace($replace, $with, $current_unquoted_string);
$current_unquoted_string = null;
}
return $accumulation;
}
在我的基准测试中,它需要两倍于上面的正则表达式方法的时间,并且当字符串长度增加时,正则表达式选项资源的使用不会增加太多。另一方面,上面的方法随着文本的长度线性增加。