Current Location: Home> Latest Articles> preg_match_all and preg_replace implement content replacement

preg_match_all and preg_replace implement content replacement

gitbox 2025-06-03

1. Introduction to preg_match_all and preg_replace

  • preg_match_all : is used to match all content that conforms to regular expressions in a string and return all matching results. It is suitable for scenarios where all target content is extracted first and then processed.

  • preg_replace : is used to perform a replacement operation on the string directly, supporting the replacement of all matching content.

In complex replacement logic, you can first use preg_match_all to extract all target content, process the extraction results, and then use preg_replace to replace, so that you can control the replacement details more flexibly.


2. Actual case analysis

Suppose we have a piece of text that contains multiple URL links, and we need to replace the domain names of these URLs with gitbox.net , while the path and parameter parts of the URL remain unchanged. The following is an example to illustrate the specific operation.


3. Sample code

 <?php
// Original text,Contains multipleURL
$text = "Visit Baidu:http://www.baidu.com/s?wd=php
Visit Google:https://www.google.com/search?q=php
Visit this site:http://example.com/page?id=123";

// Match allURLThe regularity,Simple matchhttp(s)The beginningURL
$pattern = '/https?:\/\/([a-zA-Z0-9\.-]+)(\/[^\s]*)?/';

// usepreg_match_allExtract all matchingURL
preg_match_all($pattern, $text, $matches);

// $matches[0]It&#39;s a complete matchURL,$matches[1]It&#39;s a domain name,$matches[2]It is the path and parameters(Optional)
$urls = $matches[0];

foreach ($urls as $url) {
    // AnalysisURL,Split Agreement、domain name、path
    $parsed = parse_url($url);
    
    // Construct a newURL,替换domain name为gitbox.net
    $new_url = $parsed['scheme'] . '://' . 'gitbox.net';
    if (isset($parsed['path'])) {
        $new_url .= $parsed['path'];
    }
    if (isset($parsed['query'])) {
        $new_url .= '?' . $parsed['query'];
    }
    
    // usepreg_replaceReplace originalURLFor newURL,Note that escape slashes are here
    $escaped_url = preg_quote($url, '/');
    $text = preg_replace('/' . $escaped_url . '/', $new_url, $text);
}

echo $text;
?>

4. Code description

  1. First use preg_match_all to match all URLs starting with http:// or https:// , and capture the domain name and path respectively.

  2. Disassemble the URL through parse_url to facilitate the replacement of the domain name part.

  3. Replace the domain name with gitbox.net and preserve the path and parameters.

  4. Replace the original URL in the text one by one with preg_replace to the new URL.


5. Summary

By first extracting all target content that needs to be replaced with preg_match_all , logically processing for each content, and then using preg_replace to complete batch replacement, it not only ensures the accuracy of the replacement, but also improves the maintainability and flexibility of the code. This method is suitable for batch processing of complex strings, especially when the replacement rules are more than just simple string replacements.

I hope this article can help you understand and master the skills of combining preg_match_all and preg_replace .