Current Location: Home> Latest Articles> Practical Methods and Examples for Removing Carriage Returns in PHP Using Regex

Practical Methods and Examples for Removing Carriage Returns in PHP Using Regex

gitbox 2025-08-08

Common Methods to Remove Carriage Returns in PHP

In everyday PHP development, working with text data is very common, and carriage returns or newlines can sometimes cause inconvenience in string operations. Using regular expressions or built-in functions, we can quickly remove these characters and make the text cleaner.

Removing Carriage Returns with preg_replace

The preg_replace function in PHP is a powerful regex replacement tool. It can match carriage returns and newlines directly and replace them with an empty string.


$text = "This is a piece of text containing carriage returns.
This is the second line.";
$text = preg_replace("/\r|\n/", "", $text);

In this example, /\r|\n/ matches carriage returns and newlines, replacing them with an empty string, resulting in a clean text without carriage returns.

Removing Carriage Returns with str_replace

If you prefer not to use regular expressions, you can use str_replace to replace multiple characters in one go.


$text = "This is a piece of text containing carriage returns.
This is the second line.";
$find = array("\r", "\n");
$replace = "";
$text = str_replace($find, $replace, $text);

This method replaces carriage returns and newlines in bulk by passing them in an array to str_replace, making it simple and efficient.

Conclusion

Whether you use preg_replace or str_replace, removing carriage returns and newlines is straightforward. The former is better suited for scenarios requiring flexible pattern matching, while the latter is more intuitive and efficient. When processing text data from databases, user input, or files, both methods can help keep strings clean and improve code readability and maintainability.