使用带有PHP的正则表达式替换文本

Ama*_*nda 2 php regex

我有一个类似的字符串"apple|banana|peach|cherry".

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

例如:

$input = 'There is an apple tree.';
Run Code Online (Sandbox Code Playgroud)

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

谢谢,阿曼达

anu*_*ava 8

试试这个:

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

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

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

有关更多详细信息,请查看preg_replace上的php手册

更新:@Amanda:根据您的评论,您可以将此代码修改为:

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

避免匹配弹劾和刮痧