最有效的方法来检查数组元素是否存在于字符串


Most efficient way to check if array element exists in string

我一直在寻找一种方法来检查字符串中是否存在任何值数组,但似乎PHP没有本机方法来做这件事,所以我想出了下面的方法:

我的问题-有没有更好的方法来做到这一点,因为这似乎相当低效?谢谢。

$match_found = false;
$referer = wp_get_referer();
$valid_referers = array(
    'dd-options',
    'dd-options-footer',
    'dd-options-offices'
);
/** Loop through all referers looking for a match */
foreach($valid_referers as $string) :
    $referer_valid = strstr($referer, $string);
    if($referer_valid !== false) :
        $match_found = true;
        continue;
    endif;
endforeach;
/** If there were no matches, exit the function */
if(!$match_found) :
    return false;
endif;

尝试以下函数:

function contains($input, array $referers)
{
    foreach($referers as $referer) {
        if (stripos($input,$referer) !== false) {
            return true;
        }
    }
    return false;
}
if ( contains($referer, $valid_referers) ) {
  // contains
}

这个呢:

$exists = true;
array_walk($my_array, function($item, $key) {
    $exists &= (strpos($my_string, $item) !== FALSE);
});
var_dump($exists);

这将检查字符串中是否存在任何数组值。如果只有一个缺失,您将得到一个false响应。如果您需要找出字符串中没有出现的字符,请尝试:

$exists = true;
$not_present = array();
array_walk($my_array, function($item, $key) {
    if(strpos($my_string, $item) === FALSE) {
        $not_present[] = $item;
        $exists &= false;
    } else {
        $exists &= true;
    }
});
var_dump($exists);
var_dump($not_present);

首先,替代语法很好用,但历史上它是在模板文件中使用的。因为在耦合/解耦PHP解释器插入HTML数据时,它的结构很容易阅读。

第二,如果你的代码只是检查一些东西,如果满足条件就立即返回,这通常是明智的:
$match_found = false;
$referer = wp_get_referer();
$valid_referers = array(
    'dd-options',
    'dd-options-footer',
    'dd-options-offices'
);
/** Loop through all referers looking for a match */
foreach($valid_referers as $string) :
    $referer_valid = strstr($referer, $string);
    if($referer_valid !== false) :
        $match_found = true;
        break; // break here. You already know other values will not change the outcome
    endif;
endforeach;
/** If there were no matches, exit the function */
if(!$match_found) :
    return false;
endif;
// if you don't do anything after this return, it's identical to doing return $match_found

现在由这个线程中的一些其他帖子指定。PHP有许多函数可以提供帮助。这里还有一些:

in_array($referer, $valid_referers);// returns true/false on match
$valid_referers = array(
    'dd-options' => true,
    'dd-options-footer' => true,
    'dd-options-offices' => true
);// remapped to a dictionary instead of a standard array
isset($valid_referers[$referer]);// returns true/false on match

有问题就问。