PHP: Check if string starts with a specified string.

This is a short PHP guide on how to check if a string starts with a given string. Below, I have created a simple PHP function that will do this on both a “case sensitive” and “case insensitive” basis.

Let’s take a look at the following function:

/**
 * Checks to see if a given string exists at the start of another string.
 * 
 * @param $haystack The string to search in.
 * @param $needle The string we are looking for.
 * @param bool $caseSensitive Whether we want our search to be case sensitive or not.
 * @return bool
 */
function strStartsWith($haystack, $needle, $caseSensitive = true){
    //Get the length of the needle.
    $length = strlen($needle);
    //Get the start of the haystack.
    $startOfHaystack = substr($haystack, 0, $length);
    //If we want our check to be case sensitive.
    if($caseSensitive){
        //Strict comparison.
        if($startOfHaystack === $needle){
            return true;
        }
    } else{
        //Case insensitive.
        //If the needle and the start of the haystack are the same.
        if(strcasecmp($startOfHaystack, $needle) == 0){
            return true;
        }
    }
    //No matches. Return FALSE.
    return false;
}

The function above provides a third optional parameter that allows you to specify whether or not you want the search to be case sensitive or not. By default, the function will be case sensitive.

In this function:

  1. We get the length of the string that we are looking for.
  2. Using that length, we then extract the start of the $haystack using PHP’s substr function.
  3. Finally, we compare the strings to see if they match. How we compare the strings depends on whether $caseSensitive is TRUE or FALSE. If it is TRUE, we use PHP’s triple equals for a strict comparison. If it is FALSE, we use theĀ strcasecmp function.

Examples.

In the examples below, we check to see if a string starts with the string “HELLO”. Note that in the second example, I set the third parameter to FALSE for a case insensitive comparison.

//Case sensitive.
if(!strStartsWith('hello123', 'HELLO')){
    echo 'HELLO WAS NOT found at the start of hello123 - Case sensitive', '<br>';
}

//Case insensitive.
if(strStartsWith('hello123', 'HELLO', false)){
    echo 'HELLO WAS found at the start of hello123 - Case insensitive', '<br>';
}

As you can see, it is pretty simple to use!