2011-03-08 82 views
2

我有一个类似于"apple|banana|peach|cherry"的字符串。在PHP中使用正则表达式替换文本

如何才能使用正则表达式来搜索此列表并使用特定值替换另一个字符串,如果匹配?

例如:

$input = 'There is an apple tree.'; 

修改成:"There is an <fruit>apple</fruit> tree."

感谢, 阿曼达

回答

0

preg_replace function

尽管如此,如果你想直接匹配,这是更快地使用str_replace函数或像这样的str_ireplace:

$text = "some apple text"; 
$fruits = explode("|", "apple|orange|peach"); 
$replace = array('replace apple', 'replace orange', 'replace peach'); 

$new = str_replace($fruits, $replace, $text); 
+0

Thanks!这真的很有帮助!有没有办法让像IMPEACH或SCRAPPLE这样的词不被标记为水果? – Amanda 2011-03-08 18:38:40

+1

@Amanda:根据您的评论,您可以将我的代码修改为: $ patterns =“/(^ | \ W)(苹果|香蕉|桃子|樱桃)(\ W | $)/”; $ replacements =“$ 1 $ 2 $ 3”; ,以避免匹配的弹and和零碎 – anubhava 2011-03-08 20:00:01

8

试试这个:

<?php 
$patterns ="/(apple|banana|peach|cherry)/"; 

$replacements = "<fruit>$1</fruit>"; 

$output = preg_replace($patterns, $replacements, "There is an apple tree."); 
echo $output; 
?> 

欲了解更多详情,请看看php manual on preg_replace

更新: @Amanda:根据您的评论你可以修改这个代码:

$patterns ="/(^|\W)(apple|banana|peach|cherry)(\W|$)/"; 
$replacements = "$1<fruit>$2</fruit>$3"; 

以避免匹配弹and和垃圾

0
$input = 'There is an apple tree.'; 
$output = preg_replace('/(apple|banana|peach|cherry)/', "<fruit>$1</fruit>", $input); 
+0

明白了:$ input ='有一棵苹果树。 $ output = preg_replace('/(apple | banana | cherry)/',“ $ 1”,$ input); – Amanda 2011-03-08 18:47:29

0

总体而言,可能有更好的方法来做到这一点,但这会涉及到更多关于设置和总体目标的细节。但你可以这样做:

$input = preg_replace('~(apple|banana|peach|cherry)~','&lt;fruit>$1&lt;/fruit>',$input);