Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 388
Andelas Avatar asked Dec 11 '10 23:12

Andelas


4 Answers

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

like image 188
Jonah Avatar answered Nov 20 '22 12:11

Jonah


You want the substr() function.

if(substr($source, 0, 4) == "http") {
   $source = "<a href='$source'>$source</a>";
}
like image 16
AgentConundrum Avatar answered Nov 20 '22 10:11

AgentConundrum


if(strpos($source, 'http') === 0)
    //Do stuff
like image 7
Ben Avatar answered Nov 20 '22 10:11

Ben


Use substr:

if (substr($source, 0, 4) === 'http')
like image 5
casablanca Avatar answered Nov 20 '22 12:11

casablanca