doukun1450 2011-01-24 10:34
浏览 56
已采纳

过滤URL时出错

QUESTION EDITED COMPLETELY

Hello,

I'm using this code for validating URL :

$url = preg_replace("/[^A-Za-z0-9-\/\.\:]/", "", trim($url)); // clean invalid chars and space
$url = preg_replace('%^(?!https?://).*%', 'http://$0', $url); // add HTTP:// , if there isn't
if (FALSE === strpos($url, '://www.')) // if there isn't WWW
{
    $url = str_replace('://', '://www.', $url); // add WWW
}

But there is a problem. If $url has a subdomain (like http://blog.example.com) , this codes still adding www (http://www.blog.example.com) .

How can i fix it ? If there is a subdomain, don't add www .

  • 写回答

1条回答 默认 最新

  • du6333137 2011-01-24 10:40
    关注

    I think, substr is actually supposed to be strpos?

    I doubt this code ever worked. Since you're not checking for identity (===), the condition is always true, thus prepends www.. That should work however:

    if (FALSE === strpos($url, '://www.'))
       $url = str_replace('://', '://www.', $url);
    

    There's no need to replace using expensive regular expressions in this case, so you should use str_replace.


    UPDATE: The question had been edited. I suggest the following:

    // Strip "invalid" characters
    $url = preg_replace('/[^a-z0-9\.\-]/i', '', $url);
    
    // Split URL by scheme, host, path (and possibly more)
    $parts = parse_url($domain);
    
    if (empty($parts['scheme']))
       $parts['scheme'] = 'http';
    if (!strcmp('example.com', $parts['host']))
       $parts['host'] = 'www.example.com';
    
    // Reconstruct URL
    $url = sprintf('%s://%s%s', $parts['scheme'], $parts['host'], $parts['path']);
    

    Be aware, that parse_url may return a lot more. You'll need to reconstruct accordingly.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)