Php 添加www.if';它还没有在字符串中
如果正则表达式中包含Php 添加www.if';它还没有在字符串中,php,regex,Php,Regex,如果正则表达式中包含www.,如何使用正则表达式进行字符串检查 如果字符串不包含www.,则应将其添加到字符串前面 我可以使用什么php函数来实现这一点 stackoverflow.com 应该是: www.stackoverflow.com 试一下: $input = 'stackoverflow.com'; if (strpos($input, 'www.') !== 0) { $input = 'www.' . $input; } 我敢肯定,您最好使用正则表达式,而不是正则表达式
www.
,如何使用正则表达式进行字符串检查如果字符串不包含
www.
,则应将其添加到字符串前面我可以使用什么php函数来实现这一点
stackoverflow.com
应该是:
www.stackoverflow.com
试一下:
$input = 'stackoverflow.com';
if (strpos($input, 'www.') !== 0) {
$input = 'www.' . $input;
}
我敢肯定,您最好使用正则表达式,而不是正则表达式:
<?php
$url = '//www.example.com/path?googleguy=googley';
// Prior to 5.4.7 this would show the path as "//www.example.com/path"
var_dump(parse_url($url));
?>
The above example will output:
array(3) {
["host"]=>
string(15) "www.example.com"
["path"]=>
string(5) "/path"
["query"]=>
string(17) "googleguy=googley"
}
上述示例将输出:
阵列(3){
[“主机”]=>
字符串(15)“www.example.com”
[“路径”]=>
字符串(5)“/path”
[“查询”]=>
字符串(17)“googleguy=googley”
}
一旦您将代码片段很好地分割开来,检查主机就非常简单了
$str = "stackoverflow.com";
if(substr($str, 0, 4)!="www.")
{
$str = "www.".$str;
}
echo $str;
试试这个
if(!preg_match("/^w{3}[.]/", $string))
{
$string = "www.".$string;
}
编辑:
纠正
输入:wwwut.example.com-->输出:www.wwwut.example.com它可以像
substr($str,0,4)=='www.
…一样简单,如果您计划使用它总是重定向到www.
,您最好在.htaccess
中使用RewriteRule
和RewriteCond
。简单且有效,但使用不到基本URL时可能会遇到问题。在使用协议URL(如https://example.com
他说使用regex检查是否包含www.
@但这是一个愚蠢的要求,这是可能的:-D.我刚才回答了他的问题,所有这些都会失败。另外,如果这不是一个问题,它仍然会导致int(0)
是的,我忘记了一点,对不起:-)这个点不做你认为它做的;-)它将检查我的字符串是否以“www.”开头,如果不是,则在前面添加“www.”。但是如果链接以http或https或其他方式开始,它将失败。。。但是,我的回答是正确的,不是吗?也许我在什么地方做错了。有可能上面有多处错误。我建议检查您的代码并更新您的答案