如何替换双引号和单引号之外的单词

时间:2012-06-07 09:15:03

标签: php string preg-replace

对于PHP中的自定义脚本解析器,我想替换包含双引号和单引号的多行字符串中的某些单词。 但是,只能替换外部引号的文本。

Many apples are falling from the trees.    
"There's another apple over there!"    
'Seedling apples are an example of "extreme heterozygotes".'

例如,我想将'apple'替换为'pear',但仅在引用句子之外。所以在这种情况下,只有'苹果'里面'许多苹果从树上掉下来'才会成为目标。

以上将给出以下输出:

Many pears are falling from the trees.    
"There's another apple over there!"    
'Seedling apples are an example of "extreme heterozygotes".'

我怎样才能做到这一点?

4 个答案:

答案 0 :(得分:6)

这个功能可以解决问题:

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;
}

工作原理它按引用的字符串进行拆分但包含这些引用的字符串,这样就可以在数组中交替使用非引用的,带引号的,带引号的,引用的等字符串(某些非字符串)引用的字符串可能是空白的)。然后它在替换单词和不替换之间交替,因此只替换未引用的字符串。

使用您的示例

$text = "Many apples are falling from the trees.    
        \"There's another apple over there!\"    
        'Seedling apples are an example of \"extreme heterozygotes\".'";
$replace = "apples";
$with = "pears";
echo str_replace_outside_quotes($replace,$with,$text);

<强>输出

Many pears are falling from the trees.    
"There's another apple over there!"    
'Seedling apples are an example of "extreme heterozygotes".'

答案 1 :(得分:1)

我想出了这个:

function replaceOutsideDoubleQuotes($search, $replace, $string) {
    $out = '';
    $a = explode('"', $string);
    for ($i = 0; $i < count($a); $i++) {
        if ($i % 2) $out .= $a[$i] . '"';
        else $out .= str_replace($search, $replace, $a[$i]) . '"';
    }
    return substr($out, 0, -1);
}

逻辑是:你用双引号分解字符串,所以返回字符串数组的奇数元素表示引号之外的文本,而偶数 1表示文本内部双引号。

所以,您可以通过连接原始部件和替换部件来构建输出,好吗?

此处的工作示例: http://codepad.org/rsjvCE8s

答案 2 :(得分:0)

只是想一想:通过删除引用的部分创建一个临时字符串,替换你需要的部分,然后添加你删除的引用部分。

答案 3 :(得分:0)

您可以使用preg_replace,使用正则表达式替换“”

中的单词
$search  = array('/(?!".*)apple(?=.*")/i');
$replace = array('pear');
$string  = '"There\'s another apple over there!" Seedling apples are an example of "extreme heterozygotes".';

$string = preg_replace($search, $replace, $string);

您可以通过在$ search中添加另一个RegEx以及在$ replace中添加另一个替换字符串来添加更多可搜索的对象

此RegEx使用前瞻和后瞻来查明搜索到的字符串是否在“”

相关问题