bahamut100
bahamut100

Reputation: 1837

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 :

So, the two last strings must return true.

What is the best way to find it?

Regex, or check with any substr() ?

Upvotes: 6

Views: 30604

Answers (4)

Quasdunk
Quasdunk

Reputation: 15220

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;

Upvotes: 27

Vipul jain
Vipul jain

Reputation: 129

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.

Upvotes: 3

Robin Castlin
Robin Castlin

Reputation: 10996

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.

Upvotes: 8

Tommy
Tommy

Reputation: 503

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

Upvotes: 1

Related Questions