简体   繁体   English

如何加快此PHP功能?

[英]How Can I Speed Up This PHP Function?

I am making a php filter for my webpage that checks through an array, read in through a file, to see if several user input fields (name, description, etc.) contain any of the words in the array. 我正在为我的网页制作一个php过滤器,该过滤器可以检查数组,读取文件,以查看几个用户输入字段(名称,描述等)是否包含数组中的任何单词。 I tried using the "strpos" function built into php but for whatever reason, it only detected the word if the word was the last thing in the string, ie if I were checking for the word "cat" it would detect it if it were checking "this is a cat" and "scat" but not if it were checking "cats" or "cat toy" or even just "cat " with a space after it. 我尝试使用php中内置的“ strpos”函数,但无论出于何种原因,它仅在单词是字符串中的最后一个单词时才检测到该单词,即,如果我正在检查单词“ cat”,它将检测到该单词是否为检查“这是一只猫”和“猫”,但如果检查的是“猫”或“猫玩具”,甚至只是“猫”后面有空格,则不进行检查。 To be clear, I did check to see if the strpos function was not equal to false (strpos(...)!==false). 为了清楚起见,我确实检查了strpos函数是否不等于false(strpos(...)!== false)。 So I made my own function that breaks the string up into every possible substring and checks each one to see if it equals any of the words in the array. 因此,我创建了自己的函数,该函数将字符串分解为每个可能的子字符串,并检查每个子字符串是否等于数组中的任何单词。 Is there a faster way I could do this, or a way that I could speed up the execution of this code? 有没有更快的方式可以执行此操作,或者可以加快代码执行速度? Here is the code: 这是代码:

function arrayContains($string, array $array){
$string = strtolower($string);
$len=strlen($string);
 foreach($array as $check){
    for($i=0; $i<$len; $i++){
        for($j=1; $j<=$len-$i; $j++){
            $sub=substr($string,$i,$j);
            if($sub==$check)
                return true;
        }
}
}
return false;
 }

I suspect you may have been misusing strpos() ; 我怀疑您可能一直在滥用strpos() either putting arguments in the wrong order, or not checking for a true boolean result. 要么以错误的顺序放置参数,要么不检查真实的布尔结果。 This should work: 这应该工作:

function foundInArray($string, $array){
    $string = strtolower($string);
    foreach($array as $check){
        if (strpos($string, strtolower($check)) !== false) {
            return true;
        }
    }
    return false;
}

Edit to add results: 编辑以添加结果:

php > $array = ["foo", "bar", "baz"];
php > $string = "Cheese is a food I like";
php > var_dump(foundInArray($string, $array));
bool(true)
php > $string = "Cheese is a thing I like";
php > var_dump(foundInArray($string, $array));
bool(false)

This answer, suggested by @developerwjk, helped solve my issue. @developerwjk提出的这个答案有助于解决我的问题。 I'm still open to more suggestions though if there are any. 我仍然愿意接受更多建议,即使有的话。 function arrayContains($string, array $array){ $string = strtolower($string); $len=strlen($string); for($i=0; $i<$len; $i++){ for($j=1; $j<=$len-$i; $j++){ $sub=substr($string,$i,$j); if(in_array($sub, $array)) return true; } } return false; }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM