【发布时间】:2011-04-13 18:20:49
【问题描述】:
我认为这是我需要的正则表达式。
我有一个文本输入,用户可以在其中搜索我的网站。
他们可能会在搜索短语之间使用“ELLER”这个词,在英语中等于“OR”。
但是,我的搜索引擎需要英文,所以我需要将查询字符串中的所有 ELLER 替换为 OR。
我该怎么做?
顺便说一句,是php...
谢谢
【问题讨论】:
我认为这是我需要的正则表达式。
我有一个文本输入,用户可以在其中搜索我的网站。
他们可能会在搜索短语之间使用“ELLER”这个词,在英语中等于“OR”。
但是,我的搜索引擎需要英文,所以我需要将查询字符串中的所有 ELLER 替换为 OR。
我该怎么做?
顺便说一句,是php...
谢谢
【问题讨论】:
<?php
// data
$name = "Daniel";
$order = 132456;
// String to be searched
$string = "Hi [name], thank you for the order [order_id]. The order is for [name]";
// replace rules - replace [name] with $name(Danile) AND [order_id] with $order(123456)
$text_to_send = str_replace(array('[name]', '[order_id]'), array($name, $order), $string);
// print the result
echo $text_to_send;
“嗨,Damiel,谢谢你的订单 123456。订单是给丹尼尔的”
【讨论】:
还应注意,您还可以将 str_replace 传递给要更改的值数组和要更改的值数组,例如:
str_replace(array('item 1', 'item 2'), 'items', $string);
或
str_replace(array('item 1', 'item 2'), array('1 item', '2 item'), $string);
【讨论】:
如果您要替换特定的单词,则不需要正则表达式,您可以改用str_replace:
$string = str_replace("ELLER", "OR", $string);
当您要查找的内容不是动态的时,使用 PHP 的字符串函数将比使用正则表达式更快。
如果您想确保 ELLER 仅在全字匹配时被替换,并且不包含在另一个单词中,您可以使用 preg_replace 和 word boundary 锚点 (\b):
$string = preg_replace('/\bELLER\b/', 'OR', $string);
【讨论】:
str_replace("ELLER", "OR", $string);
【讨论】:
" ELLER "和" OR "(注意空格)