Replace excess whitespaces and line-breaks with PHP?

php trim
php remove all line breaks from string
php remove line breaks and tabs
php replace with space
preg_match and replace php
replace regex php
php trim newline
replace whitespace characters php
$string = "My    text       has so    much   whitespace    




Plenty of    spaces  and            tabs";

echo preg_replace("/\s\s+/", " ", $string);

I read the PHP's documentation and follow the preg_replace's tutorial, however this code produce

My text has so much whitespace Plenty of spaces and tabs

How can I turn it into :

My text has so much whitespace Plenty of spaces and tabs

First, I'd like to point out that new lines can be either \r, \n, or \r\n depending on the operating system.

My solution:

echo preg_replace('/[ \t]+/', ' ', preg_replace('/[\r\n]+/', "\n", $string));

Which could be separated into 2 lines if necessary:

$string = preg_replace('/[\r\n]+/', "\n", $string);
echo preg_replace('/[ \t]+/', ' ', $string);

Update:

An even better solutions would be this one:

echo preg_replace('/[ \t]+/', ' ', preg_replace('/\s*$^\s*/m', "\n", $string));

Or:

$string = preg_replace('/\s*$^\s*/m', "\n", $string);
echo preg_replace('/[ \t]+/', ' ', $string);

I've changed the regular expression that makes multiple lines breaks into a single better. It uses the "m" modifier (which makes ^ and $ match the start and end of new lines) and removes any \s (space, tab, new line, line break) characters that are a the end of a string and the beginning of the next. This solve the problem of empty lines that have nothing but spaces. With my previous example, if a line was filled with spaces, it would have skipped an extra line.

Remove Whitespace and line breaks in String, The best option to use would be to use the PHP function preg_replace(), find all instances of any whitespace/line breaks and remove them from the string. Here is an example snippet of how you can use the preg_replace() function to remove all the whitespace and line breaks from a string. In PHP we have in-build functions to replace white-space from the start and end of the string these are trim, ltrim and rtrim. These functions are incapable of removing line breaks from the target string, a simple search and replace will not get line breaks. trim() function will remove white-space from start and end of the given string.

Edited the right answer. From PHP 5.2.4 or so, the following code will do:

echo preg_replace('/\v(?:[\v\h]+)/', '', $string);

PHP: Removing whitespace characters., This is a short guide on how to remove whitespace characters in PHP. we told the str_replace function to replace all space characters in our string with nothing. will not work with 'special' whitespace characters such as the “new line”. To remove newline, space and tab characters from a string, replace them with empty as shown below. replaceAll("[\ \\t ]", ""); Above, the new line, tab, and space will get replaced with empty, since we have used replaceAll() The following is the complete example. Example. Live Demo

Replace Multiple Newline, Tab, Space

$text = preg_replace("/[\r\n]+/", "\n", $text);
$text = preg_replace("/\s+/", ' ', $text);

Tested :)

Replace excess whitespaces and line-breaks with PH, Replace excess whitespaces and line-breaks with PH. 走好不送 My text has so much whitespace. Plenty of spaces and tabs. PHP. 举报问题. Tagged on: regular expressions remove whitespaces replace replace spaces tabs escapequotes October 25, 2016 October 25, 2016 php No Comments ← ESP8266 – WeMOS D1 mini – ch340

this would COMPLETELY MINIFY the entire string (such as a large blog article) yet preserving all HTML tags in place.

$email_body = str_replace(PHP_EOL, ' ', $email_body);
    //PHP_EOL = PHP_End_Of_Line - would remove new lines too
$email_body = preg_replace('/[\r\n]+/', "\n", $email_body);
$email_body = preg_replace('/[ \t]+/', ' ', $email_body);

php_strip_whitespace - Manual, Notice the PHP comments are gone, as are the whitespace and newline after the just remove excess whitespace from a string, see the example "Strip whitespace" documentation (http://www.php.net/manual/en/function.preg- replace.php). j'ai lu la documentation de PHP et j'ai suivi le tutoriel de preg_replace, cependant ce code produit . mon texte a tellement d'espaces blancs et d'onglets .

//Newline and tab space to single space

$from_mysql = str_replace(array("\r\n", "\r", "\n", "\t"), ' ', $from_mysql);


// Multiple spaces to single space ( using regular expression)

$from_mysql = ereg_replace(" {2,}", ' ',$from_mysql);

// Replaces 2 or more spaces with a single space, {2,} indicates that you are looking for 2 or more than 2 spaces in a string.

Remove unwanted empty lines | Vim Tips Wiki, The following will delete all trailing whitespace from each line, then replace three or more consecutive line endings with two line endings (a single blank line): And when you convert that PHP text into HTML(using nl2br() function), PHP interpreter will add <br> or <br /> in place of each line break. To remove line breaks, you’ll remove those escaped characters from the string. Choose any of the following two methods to accomplish it-Method 1: Using str_replace() function

Remove Line Breaks Online Tool, Line Break Removal Tool. You can remove line breaks from blocks of text but preserve paragraph breaks with this tool. If you've� The more common \s modifier includes vertical whitespace such as line breaks, which is not good for saving paragraphs. Additionally, since most of todays code works with unicode strings you need to add the /u unicode modifier. I tried to replace four sequential normal spaces by one hyphen character resulting in '- - ' instead of '-'.

Remove Extra Whitespace and Tab Space, Online tool for removing extra whitespace and tabs from text. Many other It can also delete all tab spaces if you need that option or it'll replace them with a single space. Remove Line Breaks: Remove unwanted line breaks from your text. You can combine character ranges and individual characters in trim()'s second argument (ditto for ltrim and rtrim). All of the specified characters and ranges will be used concurrently (i.e., if a character on either end of the string matches any of the specified charaters or character ranges, it will be trimmed).

Spaces Remover - Spacing Removal - Online Software Tool, How to remove double spacing? How to remove spaces in excess at the beginning or end? Spaces Removal. Text with spaces to delete� Answer: $var = str_replace(array("\r ", "\r", " "),"newline",$var); Answer to second question $var = str_replace("newline&quot;,&quot;&lt;br/&gt;&quot;,&quot

Comments
  • Same as stackoverflow.com/questions/6360566/…
  • You forgot to replace the tabs
  • @Tudor Constantin - While his example didn't have any tabs (or at least that I can tell, I didn't include them) but I've updated my answer to include them. Thanks!
  • @Francois Deschenes I removed my answer as this one is nearly complete. But let me ask, wouldn't your second replacement produce the same problem my code did? (merging spaces and tabs to a single space)
  • @Yoshi - Yes but it does it in 2 steps. First it takes care of the \r\n and then the spaces and the tabs, not all at the same time. My newest example is somewhat similar to your as it in uses \s but because I'm using the "m" modifier, ^ and $, it matches on the beginning and end of lines.
  • @Francois Deschenes I meant something different. :) Wouldn't ... '/[ \t]+/', ' ' ... merge something like ` \t\t \t ` to a single space?
  • This will not perform as required because only whitespace characters that immediately follow a vertical whitespace character (and the 1st vertical whitespace) are matched/replaced. This answer is incorrect. Proof: 3v4l.org/02ROK
  • This won't work in all cases either. If there's some additional spaces before the end of the line (i.e. "This is \r\n\r\na test"), the second preg_replace() will convert \s (spaces, tabs, new lines, line breaks) into spaces thus removing the line break in between the line (the example above will become "This is a test" in other words without any line breaks).
  • The OP requires that there are two lines in the output string, but your snippet converts all newlines to single spaces. Not only does this not produce the desired result, ereg_replace()'s docs page says: Warning This function was DEPRECATED in PHP 5.3.0, and REMOVED in PHP 7.0.0.
  • what happens if the order of whitespaces is something like "\n\n\t\t\t" - wouldn't the newlines here be replaced with tabs?