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

马克 2018-3-6 2149

<?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  
  
  
  
 ?>


欢迎联系本站长QQ:3216572
最新回复 (0)
返回