正则表达式匹配并替换由某些字符分隔的单词 [英] Regex match and replace word delimited by certain characters

查看:19
本文介绍了正则表达式匹配并替换由某些字符分隔的单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一些有关正则表达式的帮助来匹配和替换

<comma|dash|fullstop|questionmark|exclamation mark|space|start-of-string>WORD<comma|dash|fullstop|space|end-of-string>

我需要查找特定的单词(不区分大小写)

前面有:逗号、破折号、句号、问号、感叹号、空格或字符串开头

,后跟:逗号、破折号、句号、问号、感叹号、空格或字符串结尾

测试字符串: 匹配我,是的,请匹配我,但是不要匹配!匹配我,当然匹配,最后匹配

我想在PHP中用另一个字符串替换所有匹配项,因此可能需要使用PREG_REPLACE或其他什么?

推荐答案

试试

$input = "MATCH me, yes please,MATCH me but dontMATCHme!MATCH me and of course MATCH, and finally MATCH";

echo($input."<br/>");
$result = preg_replace("/
                      (?:^             # Match the start of the string
                      |(?<=[-,.?! ]))  # OR look if there is one of these chars before
                      match            # The searched word
                      (?=([-,.?! ]|$)) # look that one of those chars or the end of the line is following
                      /imx",           # Case independent, multiline and extended
                      "WORD", $input);
echo($result);

这篇关于正则表达式匹配并替换由某些字符分隔的单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆