...

View Full Version : Regular expression to check all possibilities



four0four
02-15-2010, 08:55 PM
I've been trying to figure out an easy way to check a string where spaces are allowed yet using a regular expression that matches any number of combinations with spaces in the string, without having to remove all spaces first.

For example, I have:




$mystring = preg_replace('/[^a-zA-Z0-9\s]/', '', $mystring);

$mystring = preg_replace('/apple|orange/', '', $mystring);



The above will remove "apple" or "orange", but it still allows "a pple" or "oran ge".

Now, I know I can simply remove all spaces before checking the string, but I want to allow spaces and keep the string with all original spaces intact.

So, is there a way to keep the spaces while finding a match?

Thanks!

Inigoesdr
02-15-2010, 09:35 PM
Strictly speaking you can use something like this:

$mystring = preg_replace('/\s*a\s*p\s*p\s*l\s*e\s*|\s*o\s*r\s*a\s*n\s*g\s*e\s*/', '', $mystring);
But that is not very elegant. What is the problem you're trying to solve? There might be a better way.

four0four
02-15-2010, 09:47 PM
Strictly speaking you can use something like this:

$mystring = preg_replace('/\s*a\s*p\s*p\s*l\s*e\s*|\s*o\s*r\s*a\s*n\s*g\s*e\s*/', '', $mystring);
But that is not very elegant. What is the problem you're trying to solve? There might be a better way.

Thanks, that's similar to the code that I came up with, but as you mentioned it's not very elegant, especially if I have a lot of alternates to match. :)

I even tried a way to strip the spaces and then somehow replace the spaces with some sort of character that indicates where a space was, but that takes me back to square one again.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum