Check if String Starts With http or https in PHP

This tutorial will discuss about a unique way to check if string starts with http or https in php.

To check if string starts with a specific substring or not we can use the strpos() function in PHP. It accepts two parameters,

  • First is a string
  • Second is a substring.

It returns the position of the first occurrence of the given substring in the string. If the substring does not exist in the string, then it returns false.

Now, if we want to check if the given string starts with a substring, then we can pass string and substring in the strpos() function and if it returns zero, then it means string starts with that substring.

So to check if string starts with “http” or “https” we can use the strpos() function. We have created a separate function for this,

function startsWithHttp($str)
{
    return strpos($str, "http") === 0 ||
           strpos($str, "https") === 0;
}

It accepts a string as argument, and returns true if the string starts with “http” or “https”.

Inside the function we will pass the string and the substring “http” into the strpos() function and if returns zero then it means string starts with HTTP. Otherwise we will check if string starts with https in similar way.

Let’s see the complete example,

<?php
/**
 * Checks if a string starts with "http" or "https" using strpos().
 *
 * @param string $str The string to check.
 * @return bool True if the string starts with "http" or "https", false otherwise.
 */
function startsWithHttp($str)
{
    return strpos($str, "http") === 0 ||
           strpos($str, "https") === 0;
}

$strValue = "https://thispointer.com";

if (startsWithHttp($strValue)) {
    echo "The string starts with 'http' or 'https'.";
} else {
    echo "The string does not start with 'http' or 'https'.";
}
?>

Output

The string starts with 'http' or 'https'.

Summary

We learned how to check if a string starts With http or https in PHP.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top