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?
Yes, contains is case sensitive. You can use java. util.
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.
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; }
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With