views:

39

answers:

3

I need to match the following using preg_match()

cats and dogs
catsAndDogs
i like cats and dogs

etc, so i simply stripped out the spaces and lowercased it and used that as my pattern in preg_match();

'/catsanddogs/i'

But now I need to match the following too:

cats+and+dogs
cats_and_dogs
cats+and_Dogs

So is there quick and easy way to do a string replace multiple times, other than nesting it? I want to end up with the same pattern to match with.

Thanks.

+4  A: 

try this expression '/cats([+_-])?and([+_-])?dogs/i'

edit: just saw that you don't want a + after the "and" when you already have a + before the "and". If that's right then you should use this expression:

'/cats(\+and\+|\+and_|_and_|and)dogs/i'

ITroubs
+2  A: 

I would go with @ITroubs answer in this situation, however, you can do multiple character/string replacements with strtr as follows:

$trans = array(' ' => '','+' => '','-' => '', '_' => '');
$str = 'cats+and_dogs';
echo strtr($str, $trans); // prints: catsanddogs

Read the documentation carefully before use.

rojoca
+1  A: 

OK, I don't think you have well defined your matching rules, but here is my simplified version:

(c|C)ats([+_ ][aA]|A)nd([+_ ][dD]|D)ogs

Probably you want to be case insensitive because you used /i in your pattern, but I would like to chip in with another approach.

The main differences - compared to the other answers - are the expression parts for the word bounding. I use [+_ ][aA]|A, so that the regex will match 'cats and' or 'catsAnd', but not 'catsand'. So the bottomline is, that I would only match camel case text if there is no whitespace in between.

splash