How to use regex to replace domain name in php

藏色散人
Release: 2023-03-04 11:46:02
Original
2664 people have browsed it

How to implement regular domain name replacement in php: first get the URL of the website; then create a regular expression as "$reg = '/(http):\/\/([^\/] )/i' ;"; then replace the specified domain name; and finally run the relevant PHP file.

How to use regex to replace domain name in php

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
 
 
 
 ?>
Copy after login

The above is the detailed content of How to use regex to replace domain name in php. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!