php正則實(shí)現(xiàn)替換域名的方法:首先獲取網(wǎng)站的url;然后使用正則表達(dá)式“preg_match($reg, $url,$res);”提取域名;最后通過(guò)“preg_replace”方法更換新的域名即可。
推薦:《PHP視頻教程》
正則提取的url中的域名以及替換域名的方法 preg_match()和preg_replace()
<?php //網(wǎng)站的url $url = 'http://www.baidu.com/index.php'; //正則表達(dá)式 $reg = '/(http)://([^/]+)/i'; preg_match($reg, $url,$res); /** $res的結(jié)果 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 使用后向引用緊跟數(shù)值原文 */ echo preg_replace($reg, 'http://'.$url1, $url); /** Example #2 preg_replace()中使用基于索引的數(shù)組 */ $patterns[0] = '/'.$res[2].'/'; $replacements[0] = $url1; echo preg_replace($patterns, $replacements, $url); //結(jié)果為 http://www.jingdong.com/index.php ?>