Regex: how to find a string followed by a non-alphanumeric

I am trying to use a regular expression (in php) to find a specific string, followed by a non-alphanumeric character (case insensitive).

Example String: Doggy is a lazy dog! Doggy. Dog and I. Search String: Dog Expected Result: Doggy is a lazy <a href="">dog</a>! Doggy. <a href="">Dog</a> and I. 

Therefore, it must not match Doggy because the Dog substring is not accompanied by a non-alphanumeric character.

I am trying to do something in this direction, but it does not do exactly what I want.

 preg_replace("/(dog)[^a-zA-Z0-9\s\p]/i/", "", $str); 
+5
source share
2 answers

It seems to me that what you are actually trying to do here is to match the exact words . Not necessarily a "string followed by a non-alphanumeric".

You can achieve this with the \b "word boundary" character:

 $search = "dog" preg_replace("/\b".$search."\b/i", "", $str); 
+4
source

Your regex is almost a blur, but there are a few errors:

  • I assume you want to match Dog with a space after it, if so, remove \s
  • \p not a valid regular expression.
  • After \i you should not have an extra slash. \i\ β†’ \i
  • Currently, your regular expression will delete the character without alphanumeric characters, you can fix this by surrounding it in the capture group.

You also do not have code to add anchor tags ( <a href=""></a> ).

So, I went and compiled all of this into the expression below:

 preg_replace("/(dog)([^a-zA-Z0-9])/i", '<a href="">$1</a>$2', $str); 

This returns:

 Doggy is a lazy <a href="">dog</a>! Doggy. <a href="">Dog</a> and I. 
+1
source

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


All Articles