Check if variable starts with 'http'

2019-01-19 10:23发布

问题:

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!

回答1:

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



回答2:

You want the substr() function.

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


回答3:

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


回答4:

Use substr:

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


回答5:

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