Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String contains any items in an array (case insensitive)

How can i check if a $string contains any of the items expressed in an array?

$string = 'My nAmE is Tom.'; $array = array("name","tom"); if(contains($string,$array)) { // do something to say it contains } 

Any ideas?

like image 524
tarnfeld Avatar asked Jan 23 '10 20:01

tarnfeld


People also ask

Is string contain case sensitive?

Yes, contains is case sensitive. You can use java. util.

Is string a string PHP?

You can use the PHP strpos() function to check whether a string contains a specific word or not. The strpos() function returns the position of the first occurrence of a substring in a string. If the substring is not found it returns false . Also note that string positions start at 0, and not 1.


2 Answers

I don't think there is a built-in function that will handle what you want. You could easily write a contains() function however:

function contains($str, array $arr) {     foreach($arr as $a) {         if (stripos($str,$a) !== false) return true;     }     return false; } 
like image 156
zombat Avatar answered Oct 09 '22 04:10

zombat


is that what you wanted? i hope that code is compiling :)

$string = 'My nAmE is Tom.'; $array = array("name","tom"); if(0 < count(array_intersect(array_map('strtolower', explode(' ', $string)), $array))) {   //do sth } 
like image 29
TomaszSobczak Avatar answered Oct 09 '22 02:10

TomaszSobczak