Home > Article > Backend Development > How Can I Efficiently Replace Different Newline Styles in PHP?
To replace various newline styles, such as rn, n, and r, with a uniform style (e.g., rn), the following approach is recommended:
$string = preg_replace('~\R~u', "\r\n", $string);
This utilizes PHP's PREG library to search for and replace Unicode newline sequences. The R expression matches any newline sequence in the input string. The u modifier specifies that the string should be treated as UTF-8.
If you prefer to match only carriage return (CR), linefeed (LF), or carriage return followed by linefeed (CRLF) sequences, use this line instead:
$string = preg_replace('~(*BSR_ANYCRLF)\R~', "\r\n", $string);
The following key points are worth noting:
These approaches provide a concise and efficient solution for replacing different newline styles in PHP, improving code performance and readability.
The above is the detailed content of How Can I Efficiently Replace Different Newline Styles in PHP?. For more information, please follow other related articles on the PHP Chinese website!