开发者

Find if substring exists in a string

I have a lot of strings, and I need to check if each of them contains a color.

For example :

开发者_如何学Go
  • A bird in the sky
  • 22 street of France
  • The dog is blue
  • The cat is black and white

So, the two last strings must return true.

What is the best way to find it?

Regex, or check with any substr() ?


I always work with strpos since it seems to be the fastest alternative (don't know about regex though).

if(strpos($haystack, $needle) !== FALSE) return $haystack;


In regexp you can write

preg_match_all("/(red|blue|black|white|etc)/", $haystack, $matches);

print_r($matches);

Use a loop for all the strings, and you'll easily notice which of the values from $matches you need.


if you will use strpos then it returns a position of a string it will return a number 1,2,3 etc not true or false.

And the other problem is if string exist at the start it will return 0 which will consider as false then strpos cannot find that word.


strpos or strripos in php should be able to search for a single word in a string. You may have to loop in order to search for all colors if using it though

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜