简体   繁体   English

查找数组中定义的子字符串并在PHP中返回键

[英]Find Substring Defined in Array and Return the Key in PHP

I wrote a simple function that checks if a given string contains a predefined sub-string with stripos() and returns the key of the sub string. 我编写了一个简单的函数,该函数使用stripos()检查给定的字符串是否包含预定义的子字符串,并返回该子字符串的键。 Actually I need the key string to use it in other parts of the script. 实际上,我需要密钥字符串才能在脚本的其他部分中使用它。

I'm wondering if there is a better way of doing this since currently I'm parsing the entire array and it returns the result when the match is found. 我想知道是否有更好的方法,因为目前我正在解析整个数组,找到匹配项后它会返回结果。 So if the array gets bigger, it gets slower. 因此,如果数组变大,它将变慢。

$needles = array(
    'a' => 'ab',
    'b' => 'bc',
    'c' => 'cd',
    'd' => 'de',
    'e' => 'ef'
);  
echo get_key('cd', $needles) . '<br />';
echo get_key('my_de_string', $needles) . '<br />';
echo get_key('e_ab', $needles) . '<br />';

function get_key($mystring, $needles) {
    foreach ($needles as $key => $needle)
    {
        if ((stripos($mystring, $needle)) !== false) 
        {
            return $key;
        }
    }
}

Sorry if this kind of question has been asked before. 抱歉,是否曾经有人问过这种问题。 Thanks for your information. 感谢你的信息。

You are not parsing the entire array, you are only parsing the entities the foreach loops through. 您不是在解析整个数组,而是在解析foreach循环通过的实体。 I am almost certain that this is the fastest way to do this. 我几乎可以肯定,这是最快的方法。

If you want to make it faster, depending on how many times you need to run this, and how big your array is goin to become, a trie structure would probably make this faster. 如果您想使其更快,则取决于您需要运行它多少次,以及阵列要变成多大, 特里结构可能会使它更快。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM