tags:

views:

73

answers:

4

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.

+9  A: 

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

Andy E
You want to get rid of those anchors, and change the `*` to `+`. The OP is trying to pluck matches out of the string, not match the whole thing.
Alan Moore
@Alan: yeah, the start and end anchors are gone. Thanks for the tip on the `+`, edited.
Andy E
+2  A: 

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.

John Kugelman
You should change the `*` to a `+`. Otherwise you're going to waste a lot of time replacing nothing with nothing. ;)
Alan Moore
A: 

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!!!")

Jamie Wong
+1  A: 

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]+/
M42