开发者

PHP - Checking whether a string exists in an entire array?

Basic array question:

$string = "The quick brown cat";

$check1 = "apple";
$check2 = "ball";
$check3 = "cat";

if ( (stripos($string, $check1开发者_StackOverflow社区) === false) ||
     (stripos($string, $check2) === false) ||
     (stripos($string, $check3) === false)
   ) {
   echo "Fail";
}

How do I condense the above using an array ($check[])?

Thanks!


You should still use strpos()

$checks = array('apple', 'ball', 'cat');
foreach($checks as $c){
  if(strpos($string, $c) === false){
    echo "Fail";
    break;
  }
}

benchmarks: strpos() wins

<?php

function benchmark($callback){
  echo sprintf('%-30s: ', $callback);
  $t = microtime(true);
  foreach(range(1, 10000) as $n){
    call_user_func($callback);
  }
  echo (microtime(true)-$t)."\n";
}

function smotchkkiss_strpos(){
  $string = "The quick brown cat";
  $checks = array('apple', 'ball', 'cat');
  foreach($checks as $c){
    if(strpos($string, $c) === false){
      break;
    }
  }
}

function konforce_preg_match(){
  $string = "The quick brown cat";
  preg_match('/apple|ball|cat/i', $string);
}

function konforce_preg_match_implode(){
  $string = "The quick brown cat";
  $checks = array('apple', 'ball', 'cat');
  preg_match('/'.implode('|', $checks).'/i', $string);
}


benchmark('smotchkkiss_strpos');
benchmark('konforce_preg_match');
benchmark('konforce_preg_match_implode');

# output
# smotchkkiss_strpos            : 0.020166158676147
# konforce_preg_match           : 0.032760858535767
# konforce_preg_match_implode   : 0.045573949813843

?>


You could do this:

if (preg_match('/apple|ball|cat/i', $string)) ...

Or

if (preg_match('/'.implode('|', $check).'/i', $string)) ...
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜