I have a sentence that contains a location eg activities New York for developers
in my array i have a list of locations
I want to check if the string contains a location from the array and if it does then echo it out
$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*/
}
Use 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;
}
}
Loop over your array like this:
$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;
}
}
EDIT
If you want to echo out the location just change $string
with $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;
}
}