【发布时间】: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