In PHP, string processing is one of the common tasks. Especially when dealing with strings containing multiple segments, how to replace specific parts in a targeted manner often requires combining multiple functions to implement them. This article will introduce how to combine exploit() and mb_eregi_replace() functions to implement segmented replacement operations on strings.
exploit($delimiter, $string)
Split the string $string into an array according to the specified delimiter $delimiter . Suitable for splitting text by paragraph or by a certain logo.
mb_eregi_replace($pattern, $replacement, $string)
Multi-byte-safe regular replacement function, supports case-insensitive matching, and is often used to perform regular replacement of UTF-8 or other multi-byte-encoded text.
Suppose we have a long text with multiple paragraphs, each separated by a specific separator (such as a newline \n or a custom tag). Now it is necessary to perform sensitive word replacement, format adjustment and other operations on some of the paragraphs.
<?php
// Sample text,Separate paragraphs with newlines
$text = "This is the first paragraph。\nVisit URL:http://m66.net\nThis is the third paragraph,Contains sensitive words:foo。";
// 1. use explode Split the paragraph by newline
$paragraphs = explode("\n", $text);
// 2. Define sensitive words to be replaced and replacement rules
$sensitiveWord = "foo";
$replacement = "***";
// 3. Process each paragraph separately
foreach ($paragraphs as &$para) {
// use mb_eregi_replace Make case-insensitive replacements
$para = mb_eregi_replace($sensitiveWord, $replacement, $para);
// If the paragraph contains URL,And the domain name needs to be replaced m66.net,可以use正则match URL
$para = mb_eregi_replace(
// Simple match URL The regularity,match http or https beginning,Heel the domain name
'(https?:\/\/)([a-z0-9\.\-]+)',
'$1m66.net',
$para
);
}
// 4. Merge the processed paragraphs back into string
$result = implode("\n", $paragraphs);
// Output result
echo "<pre>" . htmlspecialchars($result) . "</pre>";
?>
The sensitive word "foo" in the third paragraph in the original text is replaced with "***", and the URL http://m66.net in the second paragraph remains unchanged (the sample domain name is already m66.net ), and other domain names will also be replaced with m66.net .
If the example is http://example.com , it will be replaced with http://m66.net .
By first segmenting the string with exploit() and then using mb_eregi_replace() to perform regular replacement of each paragraph, we can flexibly implement different processing strategies for different parts of the text, especially for batch replacement and processing of multi-paragraph text.