Tutorial :PHP find words which are not in regex



Question:

I have written following regular expression /^[A-Za-z0-9-_\s]*$/ in PHP which allows numbers, letters, spaces, hyphen and underscore. I want to display those matches which are not valid against the regex i.e "My Name is Blahblah!!!" should give me "!!!" output.


Solution:1

Use the caret symbol inside the character class to invert the match and remove the start (^) and end ($) characters:

/[^A-Za-z0-9-_\s]+/  

http://php-regex.blogspot.com/2008/01/how-to-negate-character-class.html


Solution:2

If you replace all the matches with the empty string then you'll get the non-matching parts back:

preg_replace('/[A-Za-z0-9-_\s]+/', '', $string)  

This will work for any arbitrary regex, but for your specific regex @Andy's solution is simpler.

Notice that I removed the anchors ^ and $ to make this work.


Solution:3

preg_replace("/^[A-Za-z0-9-_\s]*$/","","My Name is Blahblah!!!") // Output: "!!!"

Or, if you want all the groupings of them

preg_split("/^[A-Za-z0-9-_\s]*$/","","My Name is Blahblah!!!")


Solution:4

You have to put the hiphen - at the begining or at the end of the character class or escape it, so your regex would be :

/[^-A-Za-z0-9_\s]+/  

or

/[^A-Za-z0-9_\s-]+/  

or

/[^A-Za-z0-9\-_\s]+/  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »