是否有办法接受URL并将其域名更改为.com
?
例如,如果用户要提交www.example.in
,我想检查URL是否有效,并将其更改为www.example.com
。我已经建立了一个正则表达式检查器,可以检查URL是否有效,但我不完全确定如何检查给定的扩展是否有效,然后将其更改为.com
编辑:要清楚,我实际上并没有去这些URL。我得到他们提交作为用户输入的形式,我只是存储它们。这些是我想在存储之前对URL执行的函数,仅此而已。
编辑2:一个更清楚的例子-$url = 'www.example.co.uk'
$newurl = function($url);
echo $newurl
将产生输出
www.example.com
您是否在服务器端寻找类似的东西来替换要翻译为。com的选定顶级域名列表?
<?php
$url = "www.example.in";
$replacement_tld = "com";
# array of all TLDs you wish to support
$valid_tlds = array("in","co.uk");
# possible TLD source lists
# http://data.iana.org/TLD/tlds-alpha-by-domain.txt
# https://wiki.mozilla.org/TLD_List
# from http://stackoverflow.com/a/10473026/723139
function endsWith($haystack, $needle)
{
$haystack = strtolower($haystack);
$needle = strtolower($needle);
return $needle === "" || substr($haystack, -strlen($needle)) === $needle;
}
foreach($valid_tlds as $tld){
if(endsWith($url, $tld))
{
echo substr($url, 0, -strlen($tld)) . $replacement_tld . "'n";
break;
}
}
?>
- 使用记事本等文本编辑器创建一个空文本文件,并将其保存为htaccess.txt。
301(永久)重定向:将整个站点永久指向不同的URL。这是最常见的重定向类型,在大多数情况下都很有用。在本例中,我们将重定向到"mt-example.com"域:
# This allows you to redirect your entire website to any other domain Redirect 301 / http://mt-example.com/
302(临时)重定向:将整个网站指向一个不同的临时URL。当你有一个临时的登陆页面,并计划在以后切换回你的主要登陆页面时,这对SEO很有用:
# This allows you to redirect your entire website to any other domain Redirect 302 / http://mt-example.com/
详细信息:http://kb.mediatemple.net/questions/242/How+do+I+redirect+my+site+using+a+.htaccess+file%3F
这个问题不是很清楚,我假设您希望在PHP部分实现此逻辑。
下面是解析这些字符串的有用函数:function parseUrl ( $url )
{
$r = "^(?:(?P<scheme>'w+)://)?";
$r .= "(?:(?P<login>'w+):(?P<pass>'w+)@)?";
$r .= "(?P<host>(?:(?P<subdomain>['w'.'-]+)'.)?" . "(?P<domain>'w+'.(?P<extension>'w+)))";
$r .= "(?::(?P<port>'d+))?";
$r .= "(?P<path>['w/]*/(?P<file>'w+(?:'.'w+)?)?)?";
$r .= "(?:'?(?P<arg>['w=&]+))?";
$r .= "(?:#(?P<anchor>'w+))?";
$r = "!$r!";
preg_match( $r, $url, $out );
return $out;
}
您可以解析URL,验证它,然后从结果数组中重新创建,替换您想要的任何内容。
如果你想练习regexp并创建自己的模式-这个网站将是最好的地方。
如果你的目标是将用户从一个url路由到另一个url或改变URI样式,那么你需要使用mod重写。
实际上在这种情况下,你将最终配置你的web服务器,可能是虚拟主机,因为它只会路由列出的域名(那些停放在服务器上的域名)
要在PHP中验证URL,可以使用filter_var()。
filter_var($url, FILTER_VALIDATE_URL))
然后获得顶级域名(TLD)并将其替换为。com,您可以使用以下函数: $url="http://www.dslreports.in";
$ext="com";
function change_url($url,$ext)
{
if(filter_var($url, FILTER_VALIDATE_URL)) {
$tld = '';
$url_parts = parse_url( (string) $url );
if( is_array( $url_parts ) && isset( $url_parts[ 'host' ] ) )
{
$host_parts = explode( '.', $url_parts[ 'host' ] );
if( is_array( $host_parts ) && count( $host_parts ) > 0 )
{
$tld = array_pop( $host_parts );
}
}
$new_url= str_replace($tld,$ext,$url);
return $new_url;
}else{
return "Not a valid URl";
}
}
echo change_url($url,$ext);
希望这对你有帮助!