我尝试重写纯文本搜索查询以匹配搜索引擎使用的内部格式,并且我想使用一些正则表达式来替换某些单词,但仅限于原始文本不是用双引号封装的。这就是我的意思:
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"
感谢您的时间!
答案 0 :(得分: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;