Home  >  Article  >  Backend Development  >  How to replace domain name with php regular expression

How to replace domain name with php regular expression

藏色散人
藏色散人Original
2020-08-29 09:44:354486browse

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.

How to replace domain name with php regular expression

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 = &#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
 
 
 
 ?>

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn