Php 如果url字符串没有www,如何预先添加www?
在我的网站中,我有一个表单,其中有一个URL输入字段,因此我想检查用户何时输入URL,如以下组合或www.example.com或example.com。但我想在我的数据库中存储为。如何使用PHP而不使用.htaccess或jquery或javascript验证来实现这一点Php 如果url字符串没有www,如何预先添加www?,php,url,web,Php,Url,Web,在我的网站中,我有一个表单,其中有一个URL输入字段,因此我想检查用户何时输入URL,如以下组合或www.example.com或example.com。但我想在我的数据库中存储为。如何使用PHP而不使用.htaccess或jquery或javascript验证来实现这一点 // Check, if not have http:// or https:// then prepend it if (!preg_match('#^http(s)?://#', $url)) { $url = 'htt
// Check, if not have http:// or https:// then prepend it
if (!preg_match('#^http(s)?://#', $url))
{
$url = 'http://' . $url;
}
下面的代码检查了url验证
if (filter_var($source_url, FILTER_VALIDATE_URL) === FALSE)
{
echo "<p class='error'>Oops! You Forgot to Enter Website URL</p>";
}
if(filter\u var($source\u url,filter\u VALIDATE\u url)==FALSE)
{
echo“哎呀!你忘了输入网站URL
”;
}
以下是此处发布的代码:
请注意以$host
开头的行,这是www.
的前缀。这应该打印出来http://usr:pss@www.example.com:81/mypath/myfile.html?a=b&b[]=2&b[]=3#myfragment
也就是说,我认为这是一个坏主意,原因有很多——你可能会使URL无效(例如,如果你的用户输入了m.facebook.com
,而现在你正在存储www.m.facebook.com
,它不存在?)。尝试解析URL:
如果www不存在,您需要添加它:
$uri = "http://google.com";
if (preg_match("/http:\/\/(w){3}./" , $uri)) {
echo "It matches...";
} else {
echo "not match, try to add";
if (substr($uri , 0,5) =='https') $uri = str_replace("https://" , "https://www." , $uri); else $uri = str_replace("http://" , "http://www." , $uri);
echo $uri;
}
我不建议你那样做。有时www.mysite.com
和mysite.com
不是一回事。不知道为什么。htaccess不是一个选项,它是最好的方法。您当前的编码方式可能会带来问题。也就是说,您可能需要使用PHP头。301将非www页面重定向到www页面。祝你好运。不管怎么说,问题不在这里。怎么回事?他说如果他得到http://example.com
他想要http://www.example.com
工作几分钟后,我已经完成了解决方案,但没有承诺最好的解决方案,请参见我的答案
<?php
$parsed_url = parse_url( $url );
if( $parsed_url == false)
{
// $url is invalid
}
if( $parsed_url['scheme'] != 'http' )
{
$url = 'http://' . $url;
}
$uri = "http://google.com";
if (preg_match("/http:\/\/(w){3}./" , $uri)) {
echo "It matches...";
} else {
echo "not match, try to add";
if (substr($uri , 0,5) =='https') $uri = str_replace("https://" , "https://www." , $uri); else $uri = str_replace("http://" , "http://www." , $uri);
echo $uri;
}