6

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

For example :

  • 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() ?

4 Answers 4

27

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;
Sign up to request clarification or add additional context in comments.

4 Comments

I've find a function wich use strpos, with an array of $needles
strpos does not return TRUE, but it does return FALSE so you can do if(strpos($haystack, $needle) !== FALSE) return $haystack; and another thing to remember is if you were looking for red then fred would also return a result.
@pathfinder You're absolutely right, seems like I was not paying attention :) Thanks for pointing it out.
This is faster than regex. Also beware that if strpos is case sensitive. If you need to search the substring regardless of case you should use stripos
8

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.

Comments

3

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.

1 Comment

Just use === operator
1

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

1 Comment

also saw an example somewhere about eregi eregi("(this|that)", $str) //finds this or that in $str

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.