且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-02-17 23:40:47

试试

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