carsond2704
carsond2704

Reputation: 11

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. 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. To be clear, I did check to see if the strpos function was not equal to 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;
 }

Upvotes: 0

Views: 133

Answers (2)

carsond2704
carsond2704

Reputation: 11

This answer, suggested by @developerwjk, helped solve my issue. 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; }

Upvotes: 0

miken32
miken32

Reputation: 42743

I suspect you may have been misusing 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)

Upvotes: 1

Related Questions