gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 13:55:37 24 4
gpt4 key购买 nike

对于 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".'

我怎样才能做到这一点?

最佳答案

这个函数可以解决问题:

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".'

关于php - 如何替换双引号和单引号外的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10928935/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com