缺少时将http://前缀添加到URL

Die*_*oP. 26 html php anchor http href

你好,我有一个非常简单的代码

<a href="'.$aProfileInfo['Website'].'" target="_self">
    <div class="callButton">Website</div>
</a>
Run Code Online (Sandbox Code Playgroud)

问题是,如果用户没有输入http://链接将指向我的网站,而不是指向外部网站.

如果用户没有输入http://并在不存在时自动添加,我如何签入PHP?

小智 45

我认为你最好使用内置函数parse_url(),它返回一个带有组件的关联数组

这样的事情对你有用:

 if  ( $ret = parse_url($url) ) {

      if ( !isset($ret["scheme"]) )
       {
       $url = "http://{$url}";
       }
}
Run Code Online (Sandbox Code Playgroud)

  • 这是正确的方法! (4认同)

Sat*_*ira 18

我个人使用这个,部分取自php文档

$scheme = parse_url($link, PHP_URL_SCHEME);
if (empty($scheme)) {
    $link = 'http://' . ltrim($link, '/');
}
Run Code Online (Sandbox Code Playgroud)


Chr*_*ong 16

一个简单的解决方案,可能不适用于所有情况(即'https://'):

if (strpos($aProfileInfo['Website'],'http://') === false){
    $aProfileInfo['Website'] = 'http://'.$aProfileInfo['Website'];
}
Run Code Online (Sandbox Code Playgroud)


Eva*_*edy 8

有两种方法可以解决这个问题:url解析和正则表达式.

有些人会说url解析是正确的,但正则表达式在这种情况下也能正常工作.我喜欢能够为这样的事情提供简单的单行,特别是因为这在模板文件中很常见,你可能需要在echo语句中使用单行来保持可读性.

常用表达

我们可以在preg_replace的单个函数调用中完成此操作.

preg_replace('/^(?!https?:\/\/)/', 'http://', $aProfileInfo['Website'])
Run Code Online (Sandbox Code Playgroud)

negative lookahead在查找http://或的字符串的开头使用a https://.如果找到任何一个,则不会发生替换.如果他们没有找到,它会替换字符串(0字符)与年初http://基本前面加上这个字符串,而无需修改它.

在上下文中:

<a href="'. preg_replace('/^(?!https?:\/\/)/', 'http://', $aProfileInfo['Website']).'" target="_self">
    <div class="callButton">Website</div>
</a>
Run Code Online (Sandbox Code Playgroud)

URL解析

(parse_url($aProfileInfo['Website'], PHP_URL_SCHEME) ? '' : 'http://') . $aProfileInfo['Website']
Run Code Online (Sandbox Code Playgroud)

这样做是为了找出链接中是否存在方案parse_url($aProfileInfo['Website'], PHP_URL_SCHEME).然后使用三元运算符,''如果找到一个或者找不到'http://'一个,它将输出.然后它将链接附加到该链接上.

在上下文中:

<a href="'.((parse_url($aProfileInfo['Website'], PHP_URL_SCHEME) ? '' : 'http://') . $aProfileInfo['Website']).'" target="_self">
    <div class="callButton">Website</div>
</a>
Run Code Online (Sandbox Code Playgroud)

  • 您的正则表达式很聪明,它保留了 `https://`,但它不适用于诸如 `//www.example.com` 之类的相对 url。它还将 `http://` 附加到 `ftp://` 或其他协议。试试这个:`preg_replace('/^\/\/|^(?!https?:)(?!ftps?:)/', 'http://', $src)`(注意:你可以删除如果不需要,请检查 ftp) (2认同)