簡體   English   中英

檢查字符串中是否存在數組元素的最有效方法

[英]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

詢問您是否有任何問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM