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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 13:01:03  来源:igfitidea点击:

Check if variable starts with 'http'

phpsubstringstring-comparison

提问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 strposreturns boolean falseif 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:

参考:

http://php.net/strpos

http://php.net/strpos

http://php.net/operators.comparison

http://php.net/operators.comparison

回答by AgentConundrum

You want the substr()function.

你想要这个substr()功能。

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

回答by Ben

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

回答by casablanca

Use substr:

使用substr

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

回答by ali

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