检查变量是否以'http'开头

And*_*las 21 php substring string-comparison

我确信这是一个简单的解决方案,但还没找到我需要的东西.

使用php,我有一个变量$ source.我想检查$ source是否以'http'开头.

if ($source starts with 'http') {
 $source = "<a href='$source'>$source</a>";
}
Run Code Online (Sandbox Code Playgroud)

谢谢!

Jon*_*nah 48

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

注意我使用===,不是==因为如果字符串不包含匹配则strpos返回boolean false.在PHP中,零是假的,因此需要进行严格的相等检查以消除歧义.

参考:

http://php.net/strpos

http://php.net/operators.comparison

  • 你把干草堆和针弄糊涂了. (3认同)

Age*_*rum 14

你想要这个substr()功能.

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


Ben*_*Ben 6

if(strpos($source, 'http') === 0)
    //Do stuff
Run Code Online (Sandbox Code Playgroud)


cas*_*nca 5

用途substr:

if (substr($source, 0, 4) === 'http')
Run Code Online (Sandbox Code Playgroud)