开发者

Regex match and replace word delimited by certain characters

开发者 https://www.devze.com 2023-04-06 13:08 出处:网络
I need a little help with regex to match and replace <comma|dash|fullstop|questionmark|exclamation mark|space|start-of-string>WORD<comma|dash|fullst开发者_如何学Pythonop|space|end-of-string&

I need a little help with regex to match and replace

<comma|dash|fullstop|questionmark|exclamation mark|space|start-of-string>WORD<comma|dash|fullst开发者_如何学Pythonop|space|end-of-string>

I need to find a specific WORD (case insensitive) which

is preceded by: comma or dash or fullstop or question mark or exclamation mark or space or start-of-string

and is followed by: comma or dash or fullstop or question mark or exclamation mark or space or end-of-string

test string: MATCH me, yes please,MATCH me but dontMATCHme!MATCH me and of course MATCH, and finally MATCH

I want to REPLACE all matches with another string in PHP, so i possibly need to use preg_replace or something?


Try this

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


This is not doing exactly what you asked for, but possibly fulfills your actual requirements better (which I'm guessing to be "Replace MATCH with WORD only if MATCH is an entire word, and not part of a different word"):

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

The \b are word boundary anchors that only match at the start or end of an alphanumeric word.

Result:

WORD me, yes please,WORD me but dontMATCHme!WORD me and of course WORD, and finally WORD


Here is an implementation in PHP that will do the task you described. It will replace all words with "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/>");

?>
0

精彩评论

暂无评论...
验证码 换一张
取 消