Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在PHP中使用正则表达式替换文本_Php_Regex - Fatal编程技术网

在PHP中使用正则表达式替换文本

在PHP中使用正则表达式替换文本,php,regex,Php,Regex,我有一个字符串类似于“苹果、香蕉、桃子、樱桃” 如何使用正则表达式搜索此列表,并在存在匹配项时用某个值替换另一个字符串 例如: $input = 'There is an apple tree.'; 将其更改为:“有一个水果>苹果/水果>树。” 谢谢, 阿曼达 尽管如此,如果要直接匹配,使用str_replace或str_ireplace会更快: $text = "some apple text"; $fruits = explode("|", "apple|orange|peach"); $

我有一个字符串类似于“苹果、香蕉、桃子、樱桃”

如何使用正则表达式搜索此列表,并在存在匹配项时用某个值替换另一个字符串

例如:

$input = 'There is an apple tree.';
将其更改为:
“有一个水果>苹果/水果>树。”

谢谢, 阿曼达

尽管如此,如果要直接匹配,使用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);
试试这个:

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

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

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

有关更多详细信息,请参阅

更新:
@阿曼达:根据您的意见,您可以将此代码修改为:

$patterns ="/(^|\W)(apple|banana|peach|cherry)(\W|$)/";
$replacements = "$1<fruit>$2</fruit>$3";
$patterns=“/(^ |\W)(苹果|香蕉|桃|樱桃)(\W |$)/”;
$replacements=“$1$2$3”;
为了避免匹配弹劾和报废

$input='有一棵苹果树';
$input = 'There is an apple tree.';
$output = preg_replace('/(apple|banana|peach|cherry)/', "<fruit>$1</fruit>", $input);
$output=preg_replace(“/(苹果|香蕉|桃|樱桃)/”、“$1”、$input);
总的来说,可能有更好的方法来实现这一点,但这需要您提供更多关于设置和总体目标的详细信息。但你可以这样做:

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

谢谢那真的很有帮助!有没有办法防止弹劾或刮痧这样的词被贴上水果标签?@Amanda:根据你的评论,你可以将我上面的代码修改为:$patterns=“/(^ |\W)(苹果、香蕉、桃子、樱桃)(\W |$)/”$替换=“$1$2$3”;为了避免匹配弹劾和废弃它:$input='有一棵苹果树'$输出=preg|u replace('/(苹果|香蕉|桃|樱桃)/',“$1”,$input);