Skip to content
Advertisement

Search string to see if it contains any string from an array PHP

I’m trying to check for if a string contains any blacklisted words from an array of string. This is my current code – the focus is efficiency, string from list may be empty, the string we search in is never empty:

public static function includes_from_array($stringArray, $searchInMe, $offset=0) : bool {
    // if not array just check if $stringArray exists in our $searchInMe string.
    if(!is_array($stringArray)) {
        return strpos($stringArray, $searchInMe) !== false;
    }

    foreach($stringArray as $query) {
        if ($query === '') {
            continue;
        }
        else if(strpos($searchInMe, strtolower($query), $offset) !== false) {
            return true;
        }
    }

    return false;
}

Is there a way to shorten the code quickly without harming efficiency or even improving it? The code was written as it is currently to be able to retrieve the position if required (changing from true or false to pos returned in check), however it is not required in the shortened version.

Thanks!

Advertisement

Answer

As per my understanding you soul purpose is to check any bad word is present in sentence or URL and if present then return Boolean true.

Kindly try like this:

<?php

function includes_from_array($stringArray, $searchInMe){
    if(is_array($stringArray)){
        foreach($stringArray as $arr){
            if(strpos($searchInMe,$arr) !== false){
                return true;
            }
        }
        
    }else{
        if(strpos($searchInMe,$stringArray) !== false){
            return true;
        }
    }
    return false;
}

Sample Output : https://3v4l.org/3Pefn

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement