正则表达式匹配并替换由某些字符分隔的单词

时间:2011-09-19 23:24:02

标签: regex preg-replace

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

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

我需要找到一个特定的WORD(不区分大小写)

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

然后是:逗号或短划线或完整停止或问号或感叹号或空格或字符串结尾

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

我想用PHP中的另一个字符串替换所有匹配项,所以我可能需要使用preg_replace或其他东西?

3 个答案:

答案 0 :(得分:1)

试试这个

$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);

答案 1 :(得分:0)

这是PHP中的一个实现,它将执行您描述的任务。它将用“WORD”替换所有单词。

<?php

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

echo($msg."<br/><br/>");
$msg = preg_replace("/(\w)+/", "WORD", $msg);
echo($msg."<br/>");

?>

答案 2 :(得分:0)

这并没有完全符合您的要求,但可能更好地满足您的实际要求(我猜测只有当MATCHWORD时,才会将MATCH替换为$input = 'MATCH me, yes please,MATCH me but dontMATCHme!MATCH me and of course MATCH, and finally MATCH' $result = preg_replace('/\bMATCH\b/i', "WORD", $input) 整个单词,而不是另一个单词的一部分“):

\b

WORD me, yes please,WORD me but dontMATCHme!WORD me and of course WORD, and finally WORD 是单词边界锚点,仅在字母数字词的开头或结尾处匹配。

结果:

{{1}}