2015-08-26 12 views
1

我有一个包含一个位置 如 活动,纽约开发商一句如何检查一个字符串是否包含数组中的单词然后回显?

在我的数组

我有位置

我要检查如果字符串包含从阵列中的位置,如果列表它然后回显出来

$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*/ 

} 

回答

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; 
    } 
} 
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; 
    } 
} 
+0

@martindrap:见我的编辑。 –

相关问题