String contains any items in an array (case insens

2019-01-14 02:40发布

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?

10条回答
我想做一个坏孩纸
2楼-- · 2019-01-14 03:11
<?php

$input = preg_quote('blu', '~'); // don't forget to quote input string!
$data = array('orange', 'blue', 'green', 'red', 'pink', 'brown', 'black');

$result = preg_grep('~' . $input . '~', $data);
print_r($result);

?>
查看更多
做自己的国王
3楼-- · 2019-01-14 03:14

One more workaround for contains function

function contains($string, $array, $caseSensitive = true)
{
    $stripedString = $caseSensitive ? str_replace($array, '', $string) : str_ireplace($array, '', $string);
    return strlen($stripedString) !== strlen($string);
}

PS. as for me, I'm just use it without function..

if (strlen(str_replace($array, '', $string)) !== strlen($string)) {
    // do it
}
查看更多
放我归山
4楼-- · 2019-01-14 03:15

Will this do the job?

$words = explode(" ", $string);
$wordsInArray = array();
foreach($words as $word) {
    if(in_array($word, $array)) {
        $wordsInArray[] = $word;
    }
}
查看更多
你好瞎i
5楼-- · 2019-01-14 03:15

Much simpler, please refer the link in_array

$os = array("Mac", "NT", "Irix", "Linux");
if (in_array("Irix", $os)) {
echo "Es Irix";
}
查看更多
登录 后发表回答