如何使用PHP检查URL是外部URL还是内部URL?
发布时间:2020-12-13 22:11:00 所属栏目:PHP教程 来源:网络整理
导读:我正在通过这个循环获取页面的所有ahref: foreach($html-find('a[href!="#"]') as $ahref) { $ahrefs++;} 我想做这样的事情: foreach($html-find('a[href!="#"]') as $ahref) { if(isexternal($ahref)) { $external++; } $ahrefs++;} 外在的地方是一个功能
我正在通过这个循环获取页面的所有ahref:
foreach($html->find('a[href!="#"]') as $ahref) { $ahrefs++; } 我想做这样的事情: foreach($html->find('a[href!="#"]') as $ahref) { if(isexternal($ahref)) { $external++; } $ahrefs++; } 外在的地方是一个功能 function isexternal($url) { // FOO... // Test if link is internal/external if(/*condition is true*/) { return true; } else { return false; } } 救命! 解决方法
使用
parse_url并将主机与本地主机进行比较(通常但不总是与$_SERVER [‘HTTP_HOST’]相同)
function isexternal($url) { $components = parse_url($url); return !empty($components['host']) && strcasecmp($components['host'],'example.com'); // empty host will indicate url like '/relative.php' } Hovewer这将把www.example.com和example.com视为不同的主机.如果您希望将所有子域都视为本地链接,那么该函数将会更大一些: function isexternal($url) { $components = parse_url($url); if ( empty($components['host']) ) return false; // we will treat url like '/relative.php' as relative if ( strcasecmp($components['host'],'example.com') === 0 ) return false; // url host looks exactly like the local host return strrpos(strtolower($components['host']),'.example.com') !== strlen($components['host']) - strlen('.example.com'); // check if the url host is a subdomain } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |