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);

これにより、文字列に配列値が存在するかどうかがチェックされます。1つだけ欠落している場合は、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

まず、代替構文は使いやすいですが、歴史的にはテンプレート ファイルで使用されてきました。HTMLデータを補間するために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;
        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 に答える