0

我一直在寻找一种方法来检查字符串中是否存在任何值数组,但似乎 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;
4

3 回答 3

3

尝试以下功能:

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

if ( contains($referer, $valid_referers) ) {
  // contains
}
于 2013-01-09T12:46:55.007 回答
0

那这个呢:

$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);
于 2013-01-09T12:48:15.073 回答
0

首先,替代语法很好用,但历史上它在模板文件中使用。因为它的结构在耦合/解耦 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

询问您是否有任何问题。

于 2013-01-09T12:53:26.507 回答