我有一个包含位置的句子 例如 纽约开发商活动
在我的数组中我有一个位置列表
我想检查字符串是否包含数组中的位置,如果是,则将其回显
$string = 'Activities in New York for developers';
$array = array("New York","Seattle", "San Francisco");
if(0 == count(array_intersect(array_map('strtolower', explode(' ', $string)), $array))){
echo $location /*echo out location that is in the string on its own*/
} else {
/*do nothing*/
}
答案 0 :(得分:3)
像这样遍历你的数组:
$string = 'Activities in New York for developers';
$array = array("New York","Seattle", "San Francisco");
//loop over locations
foreach($array as $location) {
//strpos will return false if the needle ($location) is not found in the haystack ($string)
if(strpos($string, $location) !== FALSE) {
echo $string;
break;
}
}
修改强>
如果您想回显该位置,只需使用$string
更改$location
:
$string = 'Activities in New York for developers';
$array = array("New York","Seattle", "San Francisco");
//loop over locations
foreach($array as $location) {
//strpos will return false if the needle ($location) is not found in the haystack ($string)
if(strpos($string, $location) !== FALSE) {
echo $location;
break;
}
}
答案 1 :(得分:1)
使用stripos
$string = 'Activities in New York for developers';
$array = array("New York","Seattle", "San Francisco");
foreach($array as $location) {
if(stripos($string, $location) !== FALSE) {
echo $string;
break;
}
}