Home >Backend Development >PHP Tutorial >How Can I Remove Newlines from a String in PHP While Avoiding Double Spaces?
Eliminating Newlines from Strings with a Space
To remove all newlines from a string, we can utilize a combination of regular expressions and PHP functions.
Given the input:
$string = "<br>put returns between paragraphs</p> <p>for linebreak add 2 spaces at end</p> <p>";<br>
We aim to output:
$string = "put returns between paragraphs for linebreak add 2 spaces at end ";<br>
We can achieve this by harnessing the following regex:
/rn|r|n/<br>
However, we must consider the possibility of double line breaks leading to double spaces. To avoid this, we utilize a more efficient regex:
$string = trim(preg_replace('/ss /', ' ', $string));<br>
This regex eliminates multiple spaces and newlines, replacing them with a single space. While it works well for our specific example, it may encounter issues when handling single newlines between words.
As an alternative, we can opt for this solution:
$string = trim(preg_replace('/s /', ' ', $string));<br>
This variation addresses the aforementioned issue by matching any number of spaces and replacing them with a single space.
The above is the detailed content of How Can I Remove Newlines from a String in PHP While Avoiding Double Spaces?. For more information, please follow other related articles on the PHP Chinese website!