php 检查变量是否以“http”开头
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4419644/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check if variable starts with 'http'
提问by Andelas
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'.
使用 php,我有一个变量 $source。我想检查 $source 是否以 'http' 开头。
if ($source starts with 'http') {
$source = "<a href='$source'>$source</a>";
}
Thanks!
谢谢!
回答by Jonah
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.
注意我使用===
, not==
因为如果字符串不包含匹配项,则strpos
返回布尔值false
。零在 PHP 中是错误的,因此需要进行严格的相等性检查以消除歧义。
Reference:
参考:
回答by AgentConundrum
回答by Ben
if(strpos($source, 'http') === 0)
//Do stuff
回答by ali
if(preg_match('/^(http)/', $source)){
...
}