Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm trying to use a regular expression (in php) to find a specific string which must be followed by a non-alpha numeric 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.

So it shouldn't match 'Doggy' because the Dog substring isn't followed by a non-alpha numeric character.

I'm trying something along these lines, but it's not doing exactly what I want.

preg_replace("/(dog)[^a-zA-Z0-9\s\p]/i/", "", $str);
like image 479
Cary Avatar asked Oct 25 '17 15:10

Cary


People also ask

How to check whether the string is alphanumeric using regular expression?

Given string str, the task is to check whether the string is alphanumeric or not by using Regular Expression . An alphanumeric string is a string that contains only alphabets from a-z, A-Z and some numbers from 0-9. This string contains all the alphabets from a-z, A-Z, and the number from 0-9. Therefore, it is an alphanumeric string.

How to check if a string contains only letters and numbers?

Check if a string only contains numbers Only letters and numbers Match elements of a url Match an email address date format (yyyy-mm-dd) Validate an ip address Url Validation Regex | Regular Expression - Taha match whole word Match or Validate phone number nginx test special characters check Match html tag Extract String Between Two STRINGS

How do you match non-alphanumeric characters?

A Regular Expression to match non-alphanumeric characters. This can be useful to match any character that is not a number of letter. [] Character set. Match any character in the set. a-z Range. Matches a character in the range “a” to “z”.

How do I check for punctuation in alphanumeric strings?

If we are checking user input and want to ensure there is no white space of punctuation preceding the alphanumeric string, we can use the start-of-string and end-of-string characters at the beginning and end of the expression: This expression will match any alphanumeric string of any length, but will not match empty strings.


1 Answers

It sounds to me like what you're actually trying to do here is perform an exact word match. Not necessarily "a string followed by a non-alphanumeric".

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

$search = "dog"
preg_replace("/\b".$search."\b/i", "", $str);
like image 57
Tom Lord Avatar answered Sep 24 '22 04:09

Tom Lord