【问题标题】:How to check if (multiple) words found in string then [duplicate]如何检查是否在字符串中找到(多个)单词然后[重复]
【发布时间】:2021-09-23 02:01:25
【问题描述】:
public static function likecheck($str, $searchTerm) {
    $searchTerm = strtolower($searchTerm);
    $str = strtolower($str);
    $pos = strpos($str, $searchTerm);
    if ($pos === false)
        return false;
    else
        return true;
}

它可以很好地匹配 $str 中的任何单个单词

$found = App\Helper::likecheck('Developers are very good','very');
if($found){
    echo 'ok';
}

但我想通过给出更多用逗号分隔的单词来检查,如果找到任何单词则返回 true

喜欢:

$found = App\Helper::likecheck('Developers are very good','very, good, gentle');
if($found){
    echo 'found';
}

但它不能,因为它只能检查一个单词。

【问题讨论】:

  • 我会建议你传递数组而不是逗号分隔的字符串

标签: php arrays string if-statement strpos


【解决方案1】:

我会建议你传递一个数组而不是单个或逗号分隔的字符串。

以及推荐使用explode()array_intersect()

public static function likecheck($str, $searchTerm =array()) {
    
    $explodedString = explode(' ', strtolower($str));
    $searchTerm = array_map('strtolower', $searchTerm);
    
    if(count(array_intersect($explodedString,$searchTerm)) > 0){
        return true;
    }else{
        return false;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-20
    • 2021-04-04
    • 2021-02-18
    • 1970-01-01
    • 1970-01-01
    • 2016-12-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多