我一直在寻找一种方法来检查字符串中是否存在任何数组值,但似乎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;
答案 0 :(得分: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
}
答案 1 :(得分: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);
答案 2 :(得分: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
询问您是否有任何问题。