提问人:Mehul Kumar 提问时间:2/1/2023 最后编辑:Mehul Kumar 更新时间:2/1/2023 访问量:157
使用带有正则表达式的 PHP 替换所有域,包括子域名
Replace all domain including subdomain name using PHP with Regex
问:
我正在使用或在PHP中替换所有域名,包括preg_replace
str_replace
www
$string = ' https://example.com, https://www.example.com, https://subdomain.example.com ';
$olddomain= "example.com";
$newdomain = "stackoverflow.com";
$output = str_replace($olddomain, $newdomain, $string);
$output = preg_replace('#(www[.])?[.]' . $olddomain. '#', $newdomain, $body);
echo $output;
我的期望:
https://example.com -> https://stackoverflow.com
https://www.example.com -> https://stackoverflow.com
https://subdomain.example.com -> https://subdomain.example.com
答:
0赞
RiggsFolly
2/1/2023
#1
不需要正则表达式,只需将 with other change 传入 .Remember 接受一系列要“更改自”和“更改为”的内容。www.
str_replace()
str_replace()
$string = ' https://example.com, https://www.example.com, https://subdomain.example.com ';
$olddomain = ["example.com",'www.'];
$newdomain = ["stackoverflow.com", ''];
$output = str_replace($olddomain, $newdomain, $string);
echo $output;
结果
https://stackoverflow.com, https://stackoverflow.com, https://subdomain.stackoverflow.com
评论
0赞
Mehul Kumar
2/1/2023
https://stackoverflow.com.stackoverflow.com
你有没有注意到这个错误。它不应该https://stackoverflow.com
https://stackoverflow.com.stackoverflow.com
0赞
RiggsFolly
2/1/2023
已经解决了,对不起,有人问了我一个问题,我分心了
0赞
Mehul Kumar
2/1/2023
没关系。是的,它有效。但是它是如何工作的。 意味着它会尝试在两种组合中匹配?["example.com",'www.'];
0赞
RiggsFolly
2/1/2023
不,它一次发生一次更改,因此如果发现更改为等,请查找$olddomain[0]
$newdomain[0]
0赞
Mehul Kumar
2/1/2023
因此,它的工作方式与for loop
PHP Array
2赞
SYdeted
2/1/2023
#2
preg_replace正则表达式。
$string = ' https://example.com, https://www.example.com, https://subdomain.example.com ';
$olddomain= "example.com";
$newdomain = "stackoverflow.com";
$output = preg_replace('#(https://(www\.)?)' . $olddomain. '#', '$1' . $newdomain, $string);
echo $output;
输出:
https://stackoverflow.com, https://www.stackoverflow.com, https://subdomain.example.com
1赞
Stellan Coder
2/1/2023
#3
不使用Regex
$string = ' https://example.com, https://www.example.com, https://subdomain.example.com ';
$olddomain= "example.com";
$newdomain = "stackoverflow.com";
$parts = explode(",", $string);
$new_parts = [];
foreach ($parts as $part) {
$new_parts[] = str_replace(['https://', 'http://', $olddomain], ['https://', 'http://', $newdomain], $part);
}
$output = implode(",", $new_parts);
echo $output;
返回
https://stackoverflow.com, https://www.stackoverflow.com, https://subdomain.example.com
1赞
Sted
2/1/2023
#4
使用数组和正则表达式
$string = ' https://example.com, https://www.example.com, https://subdomain.example.com ';
$olddomain = ["example.com", 'www\.'];
$newdomain = ["stackoverflow.com", ''];
$output = preg_replace('#https://(' . implode('|', $olddomain) . ')#', 'https://' . $newdomain[0], $string);
$output = preg_replace('#(' . $olddomain[1] . ')#', $newdomain[1], $output);
echo $output;
评论