开发者

Possible PHP function to match two keywords without regex

I've been using stripos to match single keyword within a string, however you can only define the input string, string to search and the offset... Is there a function or way i could require two keywords to be found. Such as Happy and Birthday, which would be match Happy 21st Birthday or Happy Freaking Birthday by defining both, 开发者_运维知识库Happy and Birthday separately. So that the match would come back false unless both keywords are present.


Obviously regex is more efficient, but you'd have to do:

if(strpos($yourString,"Happy") !== false && strpos($yourString,"Birthday") !== false){
    // do stuff
}


return strpos($keyword1, ...) !== false && strpos($keyword2) !== false


Simplest way is probably just to and two strpos calls

$twoNeedles = function($n1,$n2,$hay,$caseIns=false)
                {
                  $f = $caseIns ? 'stripos' : 'strpos';
                  return ($f($hay, $n1) !== false) 
                      && ($f($hay, $n2) !== false);};

echo $twoNeedles('Happy', 'Birthday', 'Happy Freakin Birthday d00d'); //true
echo $twoNeedles('Happy', 'Ice Cream', 'Happy Freakin Birthday d00d'); //false
echo $twoNeedles('HaPpY', 'bIrTH', 'Happy Freakin Birthday d00d', true); //true

And since i love to overthink

$manyNeedles =  function($n,$hay,$caseIns=false)
                {
                  $c = $caseIns ? 'stripos' : 'strpos';
                  $f = function($a,$b) use ($c,$hay) 
                         {return $a && ($c($b,$hay) !== false);};
                  return array_reduce($n,$f,true);
                };

$myNeedles = array('happy', 'birthday', 'to', 'you');
echo $manyNeedles($myNeedles, 'hap hap happy birf birthday to j000000 and you');

And now I better quit before i do it with implode and eval instead of reduce

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜