Sharky
Sharky

Reputation: 6284

Regex match and replace word delimited by certain characters

I need a little help with regex to match and replace

<comma|dash|fullstop|questionmark|exclamation mark|space|start-of-string>WORD<comma|dash|fullstop|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?

Upvotes: 1

Views: 1482

Answers (3)

Tim Pietzcker
Tim Pietzcker

Reputation: 336208

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

Upvotes: 1

stema
stema

Reputation: 92996

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

Upvotes: 1

Sky Kelsey
Sky Kelsey

Reputation: 19290

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/>");

?>

Upvotes: 0

Related Questions