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

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

我怎样才能做到这一点?

最佳答案

这个函数可以解决问题:

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/

相关文章:

Yii框架中的PHP异步方法调用

python - 如何调用需要 "quotes"字符串的函数?

php - 删除字符串,除非有空格

PHP:搜索所有 Twitter 用户名的字符串并提取它们

php - Laravel 在保存前生成 slug

javascript - backone-使用嵌套 View 保存到数据库

php - sql注入(inject)是否可以通过 file_get_contents ("php://input");或者只用 get 和 post 就可以了?

java - 删除字符串的一部分之后的所有内容

ios - 在 Swift 数组的最后一项之前添加单词 "and"

php - 使用 preg_replace 在 PHP 字符串中查找电话号码的终极方法