Andelas
Andelas

Reputation: 2052

Check if variable starts with 'http'

I'm sure this is a simple solution, just haven't found exactly what I needed.

Using php, i have a variable $source. I wanna check if $source starts with 'http'.

if ($source starts with 'http') {
 $source = "<a href='$source'>$source</a>";
}

Thanks!

Upvotes: 23

Views: 39219

Answers (6)

JSowa
JSowa

Reputation: 10592

As of PHP 8.0 there is method str_starts_with implemented:

if (str_starts_with($source, 'http')) {
    $source = "<a href='$source'>$source</a>";
} 

Upvotes: 1

ali
ali

Reputation: 41

if(preg_match('/^(http)/', $source)){
...
}

Upvotes: 1

Jonah
Jonah

Reputation: 10091

if (strpos($source, 'http') === 0) {
    $source = "<a href=\"$source\">$source</a>";
}

Note I use ===, not == because strpos returns boolean false if the string does not contain the match. Zero is falsey in PHP, so a strict equality check is necessary to remove ambiguity.

Reference:

http://php.net/strpos

http://php.net/operators.comparison

Upvotes: 52

Ben
Ben

Reputation: 16553

if(strpos($source, 'http') === 0)
    //Do stuff

Upvotes: 7

anon
anon

Reputation:

You want the substr() function.

if(substr($source, 0, 4) == "http") {
   $source = "<a href='$source'>$source</a>";
}

Upvotes: 16

casablanca
casablanca

Reputation: 70721

Use substr:

if (substr($source, 0, 4) === 'http')

Upvotes: 5

Related Questions