[英]Using Regular Expressions with PHP to replace text
我有一个类似"apple|banana|peach|cherry"
的字符串。
如果匹配,我如何使用正则表达式搜索此列表并用特定值替换另一个字符串?
例如:
$input = 'There is an apple tree.';
将其更改为: "There is an <fruit>apple</fruit> tree."
谢谢,阿曼达
尝试这个:
<?php
$patterns ="/(apple|banana|peach|cherry)/";
$replacements = "<fruit>$1</fruit>";
$output = preg_replace($patterns, $replacements, "There is an apple tree.");
echo $output;
?>
有关更多详细信息,请查看preg_replace上的php手册
更新:@Amanda:根据您的评论,您可以将此代码修改为:
$patterns ="/(^|\W)(apple|banana|peach|cherry)(\W|$)/";
$replacements = "$1<fruit>$2</fruit>$3";
避免匹配弹劾和刮痧
虽然,如果你想直接匹配,那么使用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);
$input = 'There is an apple tree.';
$output = preg_replace('/(apple|banana|peach|cherry)/', "<fruit>$1</fruit>", $input);
总体而言,可能有更好的方法来做到这一点,但这将涉及您提供有关您的设置和总体目标的更多详细信息。 但你可以这样做:
$input = preg_replace('~(apple|banana|peach|cherry)~','<fruit>$1</fruit>',$input);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.