Home > Article > Backend Development > How to replace domain name with php regular expression
php regular method to replace domain name: first get the URL of the website; then use the regular expression "preg_match($reg, $url,$res);" to extract the domain name; finally replace it with the new one through the "preg_replace" method domain name.
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 replace domain name with php regular expression. For more information, please follow other related articles on the PHP Chinese website!