Home > Article > Backend Development > How to use regex to replace domain name in php
How to implement regular domain name replacement in php: first get the URL of the website; then create a regular expression as "$reg = '/(http):\/\/([^\/] )/i' ;"; then replace the specified domain name; and finally run the relevant PHP file.
Recommended: "PHP Video Tutorial"
The domain name in the URL extracted by regular rules and the method of replacing the domain name preg_match () and 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 ?>
The above is the detailed content of How to use regex to replace domain name in php. For more information, please follow other related articles on the PHP Chinese website!