Current Location: Home> Latest Articles> How to Remove Carriage Returns from Strings in PHP: 3 Practical Methods Explained

How to Remove Carriage Returns from Strings in PHP: 3 Practical Methods Explained

gitbox 2025-06-24

1. Introduction

When working with strings during development, it's often necessary to remove carriage return characters to avoid formatting issues. This article introduces several common PHP methods to easily remove carriage returns from strings.

2. Methods to Remove Carriage Returns from Strings in PHP

2.1 Using str_replace Function

The built-in PHP function str_replace can directly replace carriage return characters in a string. Here is a sample code:


$str = "Hello,\nworld!";
$str = str_replace("\n", '', $str);
echo $str;

After execution, the newline characters in the string are removed, producing the output:

Hello,world!

2.2 Using preg_replace Function

preg_replace supports regular expression matching and replacement, suitable for more complex cases. Example:


$str = "Hello,\nworld!";
$str = preg_replace("/\n/", "", $str);
echo $str;

This method also effectively removes all carriage returns, outputting:

Hello,world!

2.3 Using strtr Function

strtr allows passing an array of replacements, useful for replacing multiple characters at once. Example for removing carriage returns:


$str = "Hello,\nworld!";
$str = strtr($str, array("\n" => ''));
echo $str;

After replacement, the output is:

Hello,world!

3. Conclusion

All three methods can easily remove carriage returns from strings. str_replace is straightforward, preg_replace is powerful for regex replacements, and strtr is great for batch replacements. Choose the method that best suits your specific needs and performance considerations to handle strings efficiently.