157

I receive a string from a database query, then I remove all HTML tags, carriage returns and newlines before I put it in a CSV file. Only thing is, I can't find a way to remove the excess white space from between the strings.

What would be the best way to remove the inner whitespace characters?

Amar
  • 13,202
  • 7
  • 53
  • 71
joepour
  • 6,831
  • 10
  • 32
  • 29
  • 6
    Please, post an sample of original string and wanted string. – Zote Nov 09 '09 at 19:53
  • Can you also clear up how the final output needs to be? Are you inserting the commas into data for CSV, getting it from a database with commas already in it, feeding strings into a function that handles the CSV insertion, etc? – Frank DeRosa Nov 09 '09 at 20:01
  • ok the final out put needs to be a string with each word seperated by a single whitespace, at the moment it is a multiple whitespaces. – joepour Nov 09 '09 at 20:05
  • 1
    @Joe, I would not waste time and would start giving credit to all those who've helped you before! :) – Frankie Nov 10 '09 at 01:10

12 Answers12

332

Not sure exactly what you want but here are two situations:

  1. If you are just dealing with excess whitespace on the beginning or end of the string you can use trim(), ltrim() or rtrim() to remove it.

  2. If you are dealing with extra spaces within a string consider a preg_replace of multiple whitespaces " "* with a single whitespace " ".

Example:

$foo = preg_replace('/\s+/', ' ', $foo);
Vaidas
  • 968
  • 9
  • 22
jW.
  • 9,280
  • 12
  • 46
  • 50
54
$str = str_replace(' ','',$str);

Or, replace with underscore, & nbsp; etc etc.

Cory Dee
  • 2,858
  • 6
  • 40
  • 55
  • 13
    This removes all whitespace. He just wants to normalise the string. – Svend Apr 28 '10 at 13:11
  • 13
    What I was looking for (even though it wasn't the question) – Robert Johnstone May 16 '12 at 14:17
  • @Gigala "What would be the best way to remove the inner whitespace characters?" was the question. This answer satisfies that perfectly. – Cory Dee Sep 13 '13 at 17:14
  • 2
    @CoryDee That's true, for that last single sentence. But in the introduction, the question is phrased as "**excess** whitespace", with emphasis on the excess. You ended up satisfying the OP's ACTUAL problem, so it doesn't much matter, but as long as we're getting *technical* about it... – Spencer Ruskin Oct 09 '13 at 23:14
  • This doesn't work if the **count** of _spaces_ is **even number**, let say: `Hi Earth` with 4 _spaces_ in between will become: `HiEarth`. This doesn't solve my problem with relevant to the question. – JJ Labajo May 06 '19 at 03:10
  • `$str = str_replace(' ',' ',$str);` to remove excess spaces – vishalknishad Apr 23 '23 at 10:52
34

none of other examples worked for me, so I've used this one:

trim(preg_replace('/[\t\n\r\s]+/', ' ', $text_to_clean_up))

this replaces all tabs, new lines, double spaces etc to simple 1 space.

Lukas Liesis
  • 24,652
  • 10
  • 111
  • 109
  • Thanks, @wp78de but for any reason, I had issues with just `\s+`. Though it was back in 2014 so maybe it is changed, haven't touched PHP for the last 3 years, can't comment but will leave current answer while it was a solution and may still be in some cases. – Lukas Liesis Oct 12 '18 at 03:57
28

$str = trim(preg_replace('/\s+/',' ', $str));

The above line of code will remove extra spaces, as well as leading and trailing spaces.

Amit Singh
  • 134
  • 12
d-_-b
  • 21,536
  • 40
  • 150
  • 256
13

If you want to replace only multiple spaces in a string, for Example: "this string have lots of space . " And you expect the answer to be "this string have lots of space", you can use the following solution:

$strng = "this string                        have lots of                        space  .   ";

$strng = trim(preg_replace('/\s+/',' ', $strng));

echo $strng;
Peanut
  • 3,753
  • 3
  • 31
  • 45
Apsar
  • 225
  • 3
  • 6
4
$str = preg_replace('/[\s]+/', ' ', $str);
Amir Fo
  • 5,163
  • 1
  • 43
  • 51
4

You can use:

$str = trim(str_replace("  ", " ", $str));

This removes extra whitespaces from both sides of string and converts two spaces to one within the string. Note that this won't convert three or more spaces in a row to one! Another way I can suggest is using implode and explode that is safer but totally not optimum!

$str = implode(" ", array_filter(explode(" ", $str)));

My suggestion is using a native for loop or using regex to do this kind of job.

Amir Fo
  • 5,163
  • 1
  • 43
  • 51
3

There are security flaws to using preg_replace(), if you get the payload from user input [or other untrusted sources]. PHP executes the regular expression with eval(). If the incoming string isn't properly sanitized, your application risks being subjected to code injection.

In my own application, instead of bothering sanitizing the input (and as I only deal with short strings), I instead made a slightly more processor intensive function, though which is secure, since it doesn't eval() anything.

function secureRip(string $str): string { /* Rips all whitespace securely. */
  $arr = str_split($str, 1);
  $retStr = '';
  foreach ($arr as $char) {
    $retStr .= trim($char);
  }
  return $retStr;
}
Fom
  • 485
  • 6
  • 14
  • 3
    It only executes it using eval if you specify the 'e' modifyier: https://www.php.net/manual/en/reference.pcre.pattern.modifiers.php#reference.pcre.pattern.modifiers.eval it has also it says that "This feature was DEPRECATED in PHP 5.5.0, and REMOVED as of PHP 7.0.0." So you can't eval stuff in preg_replace anymore. – ADJenks Sep 26 '19 at 20:54
0

To expand on Sandip’s answer, I had a bunch of strings showing up in the logs that were mis-coded in bit.ly. They meant to code just the URL but put a twitter handle and some other stuff after a space. It looked like this

? productID =26%20via%20@LFS

Normally, that would‘t be a problem, but I’m getting a lot of SQL injection attempts, so I redirect anything that isn’t a valid ID to a 404. I used the preg_replace method to make the invalid productID string into a valid productID.

$productID=preg_replace('/[\s]+.*/','',$productID);

I look for a space in the URL and then remove everything after it.

JScarry
  • 1,507
  • 1
  • 13
  • 25
0

Laravel 9.7 intruduced the new Str::squish() method to remove extraneous whitespaces including extraneous white space between words: https://laravel.com/docs/9.x/helpers#method-str-squish

Felix Geenen
  • 2,465
  • 1
  • 28
  • 37
-1
$str = "I      am a PHP   Developer";
$str_length = strlen($str);
$str_arr = str_split($str);
for ($i = 0; $i < $str_length; $i++) {
   if (isset($str_arr[$i + 1])  && $str_arr[$i] == ' ' && $str_arr[$i] == $str_arr[$i + 1]) {
       unset($str_arr[$i]);
   } 
   else {
     continue;
   }
}
echo implode("", $str_arr);
-1

I wrote recently a simple function which removes excess white space from string without regular expression implode(' ', array_filter(explode(' ', $str))).

zsoro
  • 82
  • 1
  • 10