Regex matches and replaces a word limited to 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

preceded by a comma or dash or full stop or question mark or exclamation mark or space or the beginning of a line

followed by: a comma or dash or a full or question mark or exclamation mark or a space or end of line

test line: LOOK to me, yes, please LOOK at me, but NOT MATCH! WATCH me and, of course, MATCH, and finally MATCH

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

+1
source share
3 answers

try it

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

Here is a PHP implementation that will perform the task you described. He will replace all words with the word "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
source

This is not what you requested, but it may better fulfill your actual requirements (which I suppose to be "Replace MATCH with WORD only if MATCH is a whole word, not part of another 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) 

\b are word boundary bindings that correspond only to the beginning or end of an alphanumeric word.

Result:

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

Source: https://habr.com/ru/post/1391916/


All Articles