views:

1048

answers:

5

$data contains tabs, leading spaces and multiple spaces, i wish to replace all tabs with a space. multiple spaces with one single space, and remove leading spaces.

in fact somthing that would turn

Input data:
[    asdf asdf     asdf           asdf   ]

Into output data:
[asdf asdf asdf asdf]

How do i do this?

+5  A: 
$data = trim(preg_replace('/\s+/g', '', $data));
RaYell
You also forgot to mention trim to get rid of leading spaces. Probably want to mention ltrim too, since he asked for leading spaces then illustrated both ends.
Matthew Scharley
Yeah, thanks for pointing that. In the example it's shown that both leading and trailing spaces should be removed so I updated my code.
RaYell
A: 
$data = trim($data);

That gets rid of your leading (and trailing) spaces.

$pattern = '/\s+/';
$data = preg_replace($pattern, ' ', $data);

That turns any collection of one or more spaces into just one space.

$data = str_replace("\t", " ", $data);

That gets rid of your tabs.

Gabriel Hurley
+1  A: 

Assuming the square brackets aren't part of the string and you're just using them for illustrative purposes, then:

$new_string = trim(preg_replace('!\s+!', ' ', $old_string));

You might be able to do that with a single regex but it'll be a fairly complicated regex. The above is much more straightforward.

Note: I'm also assuming you don't want to replace "AB\t\tCD" (\t is a tab) with "AB CD".

cletus
A: 
$new_data = preg_replace("/[\t\s]+/", " ", trim($data));
slosd
A: 

Trim, replace tabs and extra spaces with single spaces:

$data = preg_replace('/[ ]{2,}|[\t]/', ' ', trim($data));
ahc