When processing multibyte strings in PHP, the mb_eregi_replace function is a very practical tool. It can be used to replace regular expressions on strings, and supports multi-byte encoding while ignoring upper and lower case. This article will introduce how to use the mb_eregi_replace function to replace newline characters in text (including \r\n , \r and \n ) with newline tags in HTML <br> to correctly display the newline effect on a web page.
In HTML, ordinary line breaks are not rendered to a line break effect by the browser. Only the <br> tags can make text line breaks effective. Therefore, if a string obtained from a user input or file contains a newline character and is directly output to a web page, the text looks like a whole line without a newline. Replacing newlines with <br> tags is a common requirement for handling such text.
mb_eregi_replace is a regular replacement function for multi-byte strings in PHP, and its function signature is as follows:
string mb_eregi_replace ( string $pattern , string $replacement , string $string [, string $option = "msr" ] )
$pattern : The regular expression pattern to match (case insensitive).
$replacement : Replaced string.
$string : Enter a string.
$option : Optional regular option, default is "msr" .
The following example demonstrates how to replace a newline with <br> using mb_eregi_replace :
<?php
// Set the encoding to UTF-8
mb_internal_encoding("UTF-8");
// Pending text
$text = "This is the first line。\r\nThis is the second line。\nThis is the third line。\rThis is the fourth line。";
// use mb_eregi_replace Replace newline characters
$converted = mb_eregi_replace("\r\n|\r|\n", "<br>", $text);
// Output result
echo $converted;
?>
Regular expression \r\n|\r|\nMatch all types of newline characters:
Windows-style line breaks: \r\n
Line breaks for Mac OS (old version): \r
Unix/Linux line break: \n
Replace with <br> so that the line breaks can be displayed correctly when the web page is output.
Please make sure that the mbstring extension is enabled in the PHP environment, otherwise mb_eregi_replace will not be used.
mb_eregi_replace is case-sensitive and has no effect on newline characters, but is helpful for other character replacements.
If you only handle English and normal characters, you can also use preg_replace instead, but mb_eregi_replace supports multibyte characters better.
Using mb_eregi_replace to replace the line break character to <br> is a good way to realize the display of line breaks of multi-byte strings, and is especially suitable for text processing scenarios that include Chinese and Japanese characters such as Chinese. Mastering this technique can improve the display effect and user experience of web page text.