Remove extra spaces from string php

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.2k7 gold badges52 silver badges70 bronze badges

asked Nov 9, 2009 at 19:52

4

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

Remove extra spaces from string php

Vaidas

9089 silver badges22 bronze badges

answered Nov 9, 2009 at 20:05

jW.jW.

9,11012 gold badges46 silver badges50 bronze badges

6

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

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

answered Nov 9, 2009 at 19:53

Cory DeeCory Dee

2,7786 gold badges37 silver badges55 bronze badges

5

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.

answered Jul 3, 2014 at 7:01

Lukas LiesisLukas Liesis

22.4k8 gold badges105 silver badges101 bronze badges

1

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

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

answered Jun 19, 2013 at 0:50

d-_-bd-_-b

20.4k39 gold badges140 silver badges233 bronze badges

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,5433 gold badges29 silver badges44 bronze badges

answered May 22, 2015 at 7:18

ApsarApsar

2253 silver badges6 bronze badges

1

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

answered Jun 29, 2018 at 14:55

FomFom

4796 silver badges13 bronze badges

1

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

Amir Fo

4,4261 gold badge39 silver badges45 bronze badges

answered Apr 28, 2010 at 12:57

0

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.

answered Jul 3, 2018 at 15:41

Amir FoAmir Fo

4,4261 gold badge39 silver badges45 bronze badges

1

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.

answered Dec 3, 2013 at 23:40

Remove extra spaces from string php

JScarryJScarry

1,5091 gold badge13 silver badges25 bronze badges

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

answered May 9, 2019 at 10:59

zsorozsoro

741 silver badge9 bronze badges

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

answered Mar 23, 2019 at 10:38

How do I remove extra spaces from a string?

To eliminate spaces at the beginning and at the end of the String, use String#trim() method.

How do I trim a space in PHP?

The trim() function removes whitespace and other predefined characters from both sides of a string. Related functions: ltrim() - Removes whitespace or other predefined characters from the left side of a string. rtrim() - Removes whitespace or other predefined characters from the right side of a string.

How do you remove spaces at beginning and at the at the in string PHP?

PHP's trim() function removes all whitespace from the beginning and the end of a string. Here's an example: $myString = " Hello there! "; // Displays "Hello there!" echo trim( $myString );

What is whitespace in PHP?

A whitespace is any character that renders as a space, that is: A space character. A tab character. A carriage return character.