我怎样才能检查php中字符串的开头?

Was*_*eem 3 php string hyperlink

我想要这样的东西

  1. 用户输入网站链接

  2. 如果链接没有以"http://"开头,我需要检查链接我想在链接上附加"http://".

我怎么能用PHP做到这一点?

Tom*_*igh 11

if (stripos($url, 'http://') !== 0) {
   $url = 'http://' . $url;
}
Run Code Online (Sandbox Code Playgroud)

  • 它显然不太可读.但是在C衍生语言中有一个理由,你可以不小心写'if(a = 0)'.'if(0 = a)'会很快被抓住.虽然我个人不使用这种风格,但这是品味和编码标准的问题. (3认同)

Tom*_*ter 7

我会建议稍微改进汤姆的

if (0 !== stripos($url, 'http://') && 0 !== stripos($url, 'https://')) {
   $url = 'http://' . $url;
}
Run Code Online (Sandbox Code Playgroud)

但是,这会弄乱使用其他协议的链接(ftp:// svn:// gopher:// etc)