Remove excess whitespace from within a string

PhpString

Php Problem Overview


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?

Php Solutions


Solution 1 - Php

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);

Solution 2 - Php

$str = str_replace(' ','',$str);

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

Solution 3 - Php

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.

Solution 4 - Php

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

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

Solution 5 - Php

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;

Solution 6 - Php

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;
}

Solution 7 - Php

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

Solution 8 - Php

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.

Solution 9 - Php

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.

Solution 10 - Php

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

Solution 11 - Php

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

Solution 12 - Php

$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);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionjoepourView Question on Stackoverflow
Solution 1 - PhpjW.View Answer on Stackoverflow
Solution 2 - PhpCory DeeView Answer on Stackoverflow
Solution 3 - PhpLukas LiesisView Answer on Stackoverflow
Solution 4 - Phpd-_-bView Answer on Stackoverflow
Solution 5 - PhpApsarView Answer on Stackoverflow
Solution 6 - PhpFomView Answer on Stackoverflow
Solution 7 - PhpSandip LayekView Answer on Stackoverflow
Solution 8 - PhpAmir FoView Answer on Stackoverflow
Solution 9 - PhpJScarryView Answer on Stackoverflow
Solution 10 - PhpzsoroView Answer on Stackoverflow
Solution 11 - PhpFelix GeenenView Answer on Stackoverflow
Solution 12 - PhpShahbaz KhanView Answer on Stackoverflow