Arthur
Arthur

Reputation: 3418

How do I replace tabs with spaces within variables in PHP?

$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 this input data:

[    asdf asdf     asdf           asdf   ] 

Into output data:

[asdf asdf asdf asdf]

How do I do this?

Upvotes: 24

Views: 57385

Answers (9)

will
will

Reputation: 149

After much frustration I found this to be the best solution, as it also removes non breaking spaces which can be two characters long:

$data = html_entity_decode(str_replace(' ',' ',htmlentities($data))); $data = trim(preg_replace('/\h/', ' ', $data)); // replaces more space character types than \s

See billynoah

Upvotes: 0

Ivo Pereira
Ivo Pereira

Reputation: 3500

In case you need to remove   too.

$data = trim(preg_replace('/\s+|nbsp;/g', '', $data));

Upvotes: 0

Jeff
Jeff

Reputation: 2235

This answer takes the question completely literally: it is only concerned with spaces and tabs. Granted, the OP probably also wants to include other kinds of whitespace in what gets trimmed/compressed, but let's pretend he wants to preserve embedded CR and/or LF.

First, let's set up some constants. This will allow for both ease of understanding and maintainability, should modifications become necessary. I put in some extra spaces so that you can compare the similarities and differences more easily.

define( 'S', '[ \t]+'      ); # Stuff you want to compress; in this case ONLY spaces/tabs
define( 'L', '/\A'.S.'/'   ); # stuff on the Left edge will be trimmed
define( 'M',   '/'.S.'/'   ); # stuff in the Middle will be compressed
define( 'R',   '/'.S.'\Z/' ); # stuff on the Right edge will be trimmed
define( 'T', ' '           ); # what we want the stuff compressed To

We are using \A and \Z escape characters to specify the beginning and end of the subject, instead of the typical ^ and $ which are line-oriented meta-characters. This is not so much because they are needed in this instance as much as "defensive" programming, should the value of S change to make them needed in the future.

Now for the secret sauce: we are going to take advantage of some special semantics of preg_replace, namely (emphasis added)

If there are fewer elements in the replacement array than in the pattern array, any extra patterns will be replaced by an empty string.

function trim_press( $data ){
    return preg_replace( [ M, L, R ], [ T ], $data );
}

So instead of a pattern string and replacement string, we are using a pattern array and replacement array, which results in the extra patterns L and R being trimmed.

Upvotes: 0

dav
dav

Reputation: 9267

Just use this regex

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

it will replace all tabs and spaces by one space,

here sign + in regex means one or more times, pattern means, that wherever there are two or more spaces, replace it by one space

Upvotes: -1

ahc
ahc

Reputation: 365

Trim, replace tabs and extra spaces with single spaces:

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

Upvotes: 24

RaYell
RaYell

Reputation: 70414

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

Upvotes: 16

slosd
slosd

Reputation: 3474

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

Upvotes: 2

cletus
cletus

Reputation: 625097

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".

Upvotes: 4

Gabriel Hurley
Gabriel Hurley

Reputation: 40062

$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.

Upvotes: 6

Related Questions