Three Methods to Remove Newlines in PHP
php remove newlinesphp strip carriage returnstr_replace phppreg_replace phpPHP_EOL
Published·Modified·
PHP handles line breaks differently across operating systems:
- Linux and Unix use
\n - macOS uses
\r - Windows uses
\r\nto distinguish from Linux
Due to these differences, implementation methods vary across platforms. PHP offers three approaches to handle this:
1. Using str_replace to Replace Newlines
$str = str_replace(array("\r\n", "\r", "\n"), "", $str);
2. Using Regular Expression Replacement
$str = preg_replace('/\s*/', '', $str);
3. Using PHP's Built-in Variable (Recommended)
$str = str_replace(PHP_EOL, '', $str);
Source: Three Methods to Remove Newlines in PHP. All rights reserved by the original author.