hgerdin
hgerdin

Reputation: 637

Regex - Remove single whitespace

I´ve got a string that looks like this:

"T E S T  R E N T A L  A K T I E B O L A G"

And I want it to look like this:

"TEST RENTAL AKTIEBOLAG"

But I can´t seem to find the right regex expression for my problem. I would like to remove one single whitespace between each character.

Kind Regards / H

Upvotes: 1

Views: 274

Answers (4)

BlackWhite
BlackWhite

Reputation: 832

str_replace(' ', '', $your_string);

Upvotes: -1

A. Zalonis
A. Zalonis

Reputation: 1609

you couldnt use str_replace(' ', '', $your_string); because it will return "TESTRENTALAKTIEBOLAG" and not "TEST RENTAL AKTIEBOLAG"

But you can use bellow code:

$my_string = "T E S T  R E N T A L  A K T I E B O L A G";
$string_a = str_replace('  ','+',$my_string);
$string_b = str_replace(' ','',$string_a );
$final_string = str_replace('+',' ',$string_b);

echo $final_string;

3v4l.org

Upvotes: 0

Passerby
Passerby

Reputation: 10070

An alternative solution to @Jerry's answer:

preg_replace('# (?! )#','',$text)

regex101 demo

3v4l.org demo

Upvotes: 2

Jerry
Jerry

Reputation: 71538

You can use the regex:

\s(\s)?

And replace with $1.

regex101 demo

Upvotes: 5

Related Questions