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);
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.
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
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”.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With