开发者

Matching multiples

I need to match the following using preg_match()

cats and dogs
catsAndDogs
i l开发者_开发知识库ike 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.


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'


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜