php正则如何实现替换域名

互联网 20-8-29

php正则实现替换域名的方法:首先获取网站的url;然后使用正则表达式“preg_match($reg, $url,$res);”提取域名;最后通过“preg_replace”方法更换新的域名即可。

推荐:《PHP视频教程》

正则提取的url中的域名以及替换域名的方法 preg_match()和preg_replace()

<?php      //网站的url     $url = 'http://www.baidu.com/index.php';     //正则表达式     $reg = '/(http):\/\/([^\/]+)/i';     preg_match($reg, $url,$res);     /**  $res的结果             array (size=3) => string 'http://www.baidu.com' (length=20) => string 'http' (length=4) => string 'www.baidu.com' (length=13)     */     //要替换的位置替换成什么     $url1 = 'www.jingdong.com';       /**     Example #1 使用后向引用紧跟数值原文     */     echo preg_replace($reg, 'http://'.$url1, $url);                /**     Example #2 preg_replace()中使用基于索引的数组     */     $patterns[0] = '/'.$res[2].'/';     $replacements[0] = $url1;     echo preg_replace($patterns, $replacements, $url);     //结果为 http://www.jingdong.com/index.php        ?>

以上就是php正则如何实现替换域名的详细内容,更多内容请关注技术你好其它相关文章!

来源链接:
免责声明:
1.资讯内容不构成投资建议,投资者应独立决策并自行承担风险
2.本文版权归属原作所有,仅代表作者本人观点,不代表本站的观点或立场
标签: PHP
上一篇:php获取远程图片并下载保存到本地的方法分析 下一篇:php正则如何替换数字

相关资讯