My digital playground

PHP: Check if string contains a value in array

Filed under: Uncategorized — Andre @ 18:56 August 27th, 2009

I was writing a a very simple script to check if a visitor was a bot. Therefore I made an array of words used by bots, and soon found out that PHP got a function to check a string in an array, but not an array in a string. So I wrote a simple function, maybe someone else needs it?

// PHP Function to check if any value in an array is in a string
//
function isin_string($string, $array) {
        foreach ($array as $value) {
                if (!stristr($string, $value) === FALSE) {
                        // value is found
                        return true;
                } else {
                        // value not found
                        return false;
                }
        }
}

Or in a simpler way just implode() the array and use strrpos()

function string_in_array($string, $array) {
    $array = implode(" ", $array);
    if strrpos($array, $string) {
        // String is found
        return true;
    } else {
        // String was NOT found
        return false;
    }
}

3 Comments »

  • Thanks for this , Came across this , I was looking for the function to search an array for a string that you mentioned! Found it here for anyone else

    function stristr_array( $haystack, $needle ) {

    if ( !is_array( $haystack ) ) {

    return false;

    }

    foreach ( $haystack as $element ) {

    if ( stristr( $element, $needle ) ) {

    return $element;

    }

    }

    }

    Comment by Paris Wells — February 8th, 2011 @ 22:18

  • Thanks, it works excellent to check if any element of an array are substrings contained in a string. Very much recommended!

    Comment by RK — August 2nd, 2011 @ 17:58

  • Alternatively you could use preg_match, example being

    $botlist = ‘/(Google|msnbot|Rambler|Yahoo|AbachoBOT|accoona|dotbot|AcioRobot|ASPSeek|CocoCrawler|Dumbot|FAST-WebCrawler|GeonaBot|Gigabot|Lycos|MSRBOT|Scooter|AltaVista|IDBot|eStyle|Scrubby|Googlebot|Yahoo! Slurp|VoilaBot|ZyBorg|WebCrawler|DeepIndex|Teoma|appie|HenriLeRobotMirago|psbot|Szukacz|Openbot|Naver)+/i’;

    if (preg_match($botlist,$_SERVER['HTTP_USER_AGENT'])) $isBrowser = false;

    Comment by Nick — February 21st, 2012 @ 23:42

RSS feed for comments on this post. TrackBack URL

Leave a comment