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


<?php 
    //网站的url
    $url = 'http://www.baidu.com/index.php';
    //正则表达式
    $reg = '/(http):\/\/([^\/]+)/i';
    preg_match($reg, $url,$res);
    /**  $res的结果
            array (size=3)
              0 => string 'http://www.baidu.com' (length=20)
              1 => string 'http' (length=4)
              2 => 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



 ?>

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM