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

Nic*_*ick 5 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".'
Run Code Online (Sandbox Code Playgroud)

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

以上将给出以下输出:

Many pears are falling from the trees.    
"There's another apple over there!"    
'Seedling apples are an example of "extreme heterozygotes".'
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?

Tim*_*imm 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;
}
Run Code Online (Sandbox Code Playgroud)

它是如何工作的它按引用的字符串进行拆分但包括这些引用的字符串,这会在数组中为您提供交替的非引用,引用,引用,引用等字符串(某些非引用字符串可能为空).然后它在替换单词和不替换之间交替,因此只替换未引用的字符串.

用你的例子

$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);
Run Code Online (Sandbox Code Playgroud)

产量

Many pears are falling from the trees.    
"There's another apple over there!"    
'Seedling apples are an example of "extreme heterozygotes".'
Run Code Online (Sandbox Code Playgroud)