dongliang1865 2013-08-31 07:05
浏览 86
已采纳

PHP函数将“http://”添加到字符串

I often use the following code on my WordPress builds in order to help prevent invalid links being added:

// add http:// if necessary
function addHttp($url) {
    if(substr($url, 0, 4) == 'www.') {
        $url = 'http://' . $url;
    }
    return $url;
}

But this won't work should anyone add a link that does include a 'http://' but doesn't include a 'www.' in there too.

Does anyone know how I can modify my script to cater for this?

  • 写回答

2条回答 默认 最新

  • doujing1156 2013-08-31 07:06
    关注
    1. Don't assume that a URL will have www in it. Adding it will often break URLs.
    2. Test to see if it starts with http or https and add the scheme if it doesn't

    So:

    function addHttp($url) {
      if(substr($url, 0, 4) != 'http') {
        $url = 'http://' . $url;
      }
      return $url;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部