How to check if string starts with in PHP

How to check if string starts with in PHP

In this article lets understand how to check if string starts with in PHP.

PHP provides many ways to find out if a string starts with any other specific string, let’s explore them.

Among various versions of PHP the latest adds new functions which provides simple way to do so.

PHP version 8 or greater :

str_starts_with – This function is added in newer versions which make the operation simple and easy.


str_starts_with("https://codingsolutionspoint.com","https");
Result : true


// param 1 - The string to search in.
// param 2 - The string to search for.
// Result : true / false

PHP version 7 or below :

So for 7 or older versions we don’t have direct simple functions but various other methods we can use to find if string starts with something or not.

1. substr()

We can use substr function by defining correct offset and length. Below given setting is required to check string starts with. we can use this function for other checks as well by defining different offset and length setting. For our case check below example :

$str = "https://codingsolutionspoint.com";
if (substr($str, 0, 5) == "https") {
     echo "The string starts with https";
}

// param1 - $str -> The string to search in.
// param2 - 0 -> To start search from 0 index
// param3 - length -> How many letters from the offset to search for.

2. strpos()

The strpos() function we can use by matching the position of the string. We provide both the strings to the function and offset from where we want to match. See below example :

$str = "https://codingsolutionspoint.com";
if (strpos($str, "https",0) === 0) {
echo "The string starts with https";
}

// param1 - $str -> The string to search in.
// param2 - The string to search for.
// param3 - offset -> to start search from 0 index.

3. preg_match()

Similarly, we can use preg_match() works same as above functions but it uses regular expression to match the string and hence we can find our solution.

$str = "https://codingsolutionspoint.com";
if (preg_match("/^https/", $str)) {
echo "The string starts with https";
}

// param 1 - regular expression for string to match
// param 2 - string to check from.

So that’s it. These are the various ways on how to check if string starts with in PHP. Hope this finds you helpful.

See other articles on PHP here.