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.
views:
73answers:
4Use 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
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.
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!!!")
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]+/