Manoj K
Manoj K

Reputation: 389

Remove extra spaces but not space between two words

I want to remove extra spaces present in my string. I have tried trim,ltrim,rtrim and others but non of them are working and even tried the below stuffs.

//This removes all the spaces even the space between the words 
// which i want to be kept
$new_string = preg_replace('/\s/u', '', $old_string); 

Is there any solution for this ?

Updated:-

Input String:-

"
Hello Welcome
                             to India    "

Output String:-

"Hello Welcome to India"

Upvotes: 21

Views: 26731

Answers (6)

DragonFire
DragonFire

Reputation: 4082

Try this, this will also remove all &nbsp

$node3 = htmlentities($node3, null, 'utf-8');
$node3 = str_replace(" ", "", $node3);
$node3 = html_entity_decode($node3);

$node3 = preg_replace('/^\s+|\s+$|\s+(?=\s)/', '', $node3);

Upvotes: 0

gaurangkathiriya
gaurangkathiriya

Reputation: 741

If You remove single space between word. try it

trim(str_replace(' ','','hello word'));

Upvotes: 0

Tim Pietzcker
Tim Pietzcker

Reputation: 336108

OK, so you want to trim all whitespace from the end of the string and excess whitespace between words.

You can do this with a single regex:

$result = preg_replace('/^\s+|\s+$|\s+(?=\s)/', '', $subject);

Explanation:

^\s+      # Match whitespace at the start of the string
|         # or
\s+$      # Match whitespace at the end of the string
|         # or
\s+(?=\s) # Match whitespace if followed by another whitespace character

Like this (example in Python because I don't use PHP):

>>> re.sub(r"^\s+|\s+$|\s+(?=\s)", "", "  Hello\n   and  welcome to  India   ")
'Hello and welcome to India'

Upvotes: 15

jamb
jamb

Reputation: 146

If you want to remove multiple spaces within a string you can use the following:

$testStr = "                  Hello Welcome
                         to India    ";
$ro = trim(preg_replace('/\s+/', ' ', $testStr));

Upvotes: 5

h.s.o.b.s
h.s.o.b.s

Reputation: 1319

$cleanStr = trim(preg_replace('/\s\s+/', ' ', str_replace("\n", " ", $str)));

Upvotes: 47

Mohit S
Mohit S

Reputation: 14024

I Think what we are supposed to do here is we should not look for 1 space we should look for consecutive two spaces and then make it one. So this way it would not replace the space between the text and also remove any other space.

$new_string= str_replace(' ', ' ', $old_string)

for more on Str Replace

Upvotes: 3

Related Questions