首頁  >  文章  >  後端開發  >  php如何使用正規替換域名

php如何使用正規替換域名

藏色散人
藏色散人原創
2020-08-13 09:33:552691瀏覽

php正規替換網域的實作方法:先取得網站的url;然後建立正規表示式為「$reg = '/(http):\/\/([^\/] )/i' ;」;接著替換指定網域名稱;最後執行相關PHP檔案即可。

php如何使用正規替換域名

推薦:《PHP影片教學

正則擷取的url中的網域名稱以及替換網域的方法preg_match ()和preg_replace()

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

以上是php如何使用正規替換域名的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn