【问题标题】:Which member of array does the string contain in PHP?PHP 中字符串包含数组的哪个成员?
【发布时间】:2014-02-18 10:42:31
【问题描述】:

如何检查字符串是否包含数组的成员,并返回相关成员的索引(整数)?

假设我的字符串是这样的:

$string1 = "stackoverflow.com";
$string2 = "superuser.com";
$r = array("queue" , "stack" , "heap");

get_index($string1 , $r); // returns 1
get_index($string2 , $r); // returns -1 since string2 does not contain any element of array

我怎样才能以优雅(简短)和高效的方式编写这个函数?

我找到了一个检查字符串是否包含数组成员的函数(表达式?):

(0 < count(array_intersect(array_map('strtolower', explode(' ', $string)), $array)))

但这是一个布尔值。 count() 函数是否在此语句中返回我想要的内容?

感谢您的帮助!

【问题讨论】:

  • 仅供参考,您的单行代码并不是最好的代码。爆炸、转换和相交是对大字符串/数组的“繁重”操作,可以更轻松地完成:)

标签: php arrays string contains


【解决方案1】:
function get_index($str, $arr){
    foreach($arr as $key => $val){
    if(strpos($str, $val) !== false)
    return $key;
    }
return -1;
}

演示:https://eval.in/95398

【讨论】:

  • 这只返回数组的第一个键。 TS 想要(如果我理解正确的话)匹配元素的数量,而不仅仅是第一个键。除此之外,请查看我的代码中的break;
  • 我确实想要索引。对不起,如果我把问题表述得不好。这个答案正是我正在寻找的。虽然我没有测试其他人,但感谢所有答案!
  • 这只会返回 FIRST 键。如果你想要所有的钥匙,你可以用我的功能稍作改动
【解决方案2】:

这将在你的数组中找到匹配元素的数量,如果你想要所有匹配的键,请使用注释行代替:

function findMatchingItems($needle, $haystack){
    $foundItems = 0; // start counter
    // $foundItems = array(); // start array to save ALL keys
    foreach($haystack as $key=>$value){ // start to loop through all items
        if( strpos($value, $needle)!==false){ 
            ++$foundItems; // if found, increase counter
            // $foundItems[] = $key; // Add the key to the array
        }
    }
    return $foundItems; // return found items
}

findMatchingItems($string1 , $r);
findMatchingItems($string2 , $r);

如果要返回所有匹配的键,只需将 $foundItems 更改为数组并在 if 语句中添加键(切换到注释行)。

如果你只想知道某件事是否匹配

function findMatchingItems($needle, $haystack){
    if( strpos($value, $needle)!==false){ 
        return true;
        break; // <- This is important. This stops the loop, saving time ;)
    }
    return false;// failsave, if no true is returned, this will return
}

【讨论】:

    【解决方案3】:

    我会做这样的功能:

    function getIndex($string, $array) {
        $index = -1;
        $i = 0;
        foreach($array as $array_elem) {
            if(str_pos($array_elem, $string) !== false) {
                $index = $i;
            }
            $i++;
        }
        return $index;
    }
    

    【讨论】:

    • 虽然这行得通,但我认为 TS 的意思不是获取索引,而是匹配元素的数量
    • 另外,您现在运行$i++,这可能不正确。如果您有从 A 到 Z 的键,则键 7 将毫无意义:) 我建议使用 ($array as $key=&gt;value) 方法,并返回 $key
    • 哈哈,另外:请看我的回答,最后一个例子,然后是break;
    • 我最终投了反对票,这个答案没有提供问题的解决方案,如果你解决了所有“问题”,它将与 Sharanya 的答案相同(这也是不正确的)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-04-11
    • 1970-01-01
    • 2013-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多