检查变量是否以"http"开头 [英] Check if variable starts with 'http'

查看:90
本文介绍了检查变量是否以"http"开头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我确定这是一个简单的解决方案,只是没有找到我真正需要的东西.

I'm sure this is a simple solution, just haven't found exactly what I needed.

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

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>";
}

谢谢!

推荐答案

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

请注意,我使用的是===,而不是==,因为如果字符串不包含匹配项,则strpos返回布尔值false.在PHP中,零是假的,因此必须进行严格的相等性检查才能消除歧义.

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.

参考:

http://php.net/strpos

http://php.net/operators.comparison

这篇关于检查变量是否以"http"开头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆