dongpang2483
2015-08-26 11:25
浏览 83
已采纳

如何检查字符串是否包含数组中的单词然后回显它?

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

}

图片转代码服务由CSDN问答提供 功能建议

我有一个包含位置的句子 eg activities纽约开发人员

在我的数组中我有一个位置列表

我想检查字符串是否包含数组中的位置,如果确实存在,则将其回显出来 $ string ='纽约开发商活动'; $ array = array(“纽约”,“西雅图”,“旧金山”); if(0 == count( array_intersect(array_map('strtolower',explode('',$ string)),$ array))){ echo $ location / *回显出字符串中的位置* / } 否{ / *什么都不做* / }

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • douyan2680 2015-08-26 11:28
    已采纳

    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;
        }
    }
    
    已采纳该答案
    打赏 评论
  • dpsu84620 2015-08-26 11:27

    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;
        }
    }
    
    打赏 评论

相关推荐 更多相似问题