【问题标题】:PHP Regex - Replace text not contained in quotesPHP Regex - 替换引号中未包含的文本
【发布时间】:2014-03-13 12:57:40
【问题描述】:

我正在尝试重写纯文本搜索查询以匹配我们搜索引擎使用的内部格式,并且我想使用一些正则表达式来替换某些单词,但前提是原始文本未被封装双引号。这就是我的意思:

  • rock from adelaide 将变为 rock location:adelaide
  • beep "rock from adelaide" boop 将保留为 beep "rock from adelaide" boop
  • find me some rock from "adelaide" 将变为 find me some rock location:"adelaide"
  • is there "any rock from adelaide please", thanks 将保留为 is there "any rock from adelaide please", thanks

我是一个正则表达式菜鸟,无论我阅读和研究多少,我都无法在这里找到解决方案。我可以轻松地对单词from 进行搜索和替换,但仅匹配外部引号完全超出了我的范围。

这是我目前所拥有的,但显然它不起作用:

<?php
  $pattern = '%(*ANY)(.*?(")(?(2).*?")(.*?))*?from %s';
  $replace = '\1location:'; 
  $subject = 'find me some rock from adelaide but not "rock from perth"';
  print preg_replace($pattern, $replace, $subject);
?>

预期的输出是:

find me some rock location:adelaide but not "rock from perth"

实际输出为:

find me some rock location:adelaide but not "rock location:perth"

感谢您的宝贵时间!

【问题讨论】:

    标签: php regex preg-replace


    【解决方案1】:

    您想替换不在双引号之间的单词。因此,当我们分解字符串时,数组的偶数索引将是我们的目标(也是 0)。我们需要的是创建循环,它将跳过 2 个索引并在那里使用 str_replace()。会是这样的:

    $test = '"rock from perth" xxxxxxx "afjakdhfa" find me some rock from adelaide but not ';
    $array = explode('"', $test);
    $count = count($array);
    for($i = 0; $i < $count; $i+=2)
    {
        $array[$i] = str_replace('from', 'location:', $array[$i]);
    }
    $test = implode('"', $array);
    echo $test;
    

    【讨论】:

    • 谢谢您,这非常有效,非常感谢您的帮助。虽然,为了获得知识,我仍然很想知道是否有一个正则表达式模式可以做同样的事情。
    • 将很难,因为正则表达式模式不知道该字符串是否介于两者之间。从$test 变量:"rock from perth"" xxxxxxx " 之间有双引号,但 xxxxxxx 实际上不是在之间:) 如果有一种方法,我会同时感到惊讶和惊讶。
    猜你喜欢
    • 2011-05-17
    • 2014-01-18
    • 1970-01-01
    • 1970-01-01
    • 2015-12-13
    • 2011-09-14
    • 1970-01-01
    • 2016-06-08
    • 2020-11-13
    相关资源
    最近更新 更多