How to check if a string starts with a specified string?


I'm trying to check if a string starts with http. How can I do this check?

$string1 = '';
$string2 = '';
10/25/2016 10:48:26 AM

Accepted Answer

Use the substr function to return a part of a string.

substr( $string_n, 0, 4 ) === "http"

If you're trying to make sure it's not another protocol. I'd use http:// instead, since https would also match, and other things such as

substr( $string_n, 0, 7 ) === "http://"

And in general:

substr($string, 0, strlen($query)) === $query
4/16/2019 2:02:26 PM

There is also the strncmp() function and strncasecmp() function which is perfect for this situation:

if (strncmp($string_n, "http", 4) === 0)

In general:

if (strncmp($string_n, $prefix, strlen($prefix)) === 0)

The advantage over the substr() approach is that strncmp() just does what needs to be done, without creating a temporary string.


You can use a simple regex (updated version from user viriathus as eregi is deprecated)

if (preg_match('#^http#', $url) === 1) {
    // Starts with http (case sensitive).

or if you want a case insensitive search

if (preg_match('#^http#i', $url) === 1) {
    // Starts with http (case insensitive).

Regexes allow to perform more complex tasks

if (preg_match('#^https?://#i', $url) === 1) {
    // Starts with http:// or https:// (case insensitive).

Performance wise, you don't need to create a new string (unlike with substr) nor parse the whole string if it doesn't start with what you want. You will have a performance penalty though the 1st time you use the regex (you need to create/compile it).

This extension maintains a global per-thread cache of compiled regular expressions (up to 4096).


You can check if your string starts with http or https using the small function below.

function has_prefix($string, $prefix) {
   return substr($string, 0, strlen($prefix)) == $prefix;

$url   = '';
echo 'the url ' . (has_prefix($url, 'http://')  ? 'does' : 'does not') . ' start with http://';
echo 'the url ' . (has_prefix($url, 'https://') ? 'does' : 'does not') . ' start with https://';

Also work:

if (eregi("^http:", $url)) {
 echo "OK";

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]