Reputation: 389
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
Reputation: 4082
Try this, this will also remove all  
$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
Reputation: 741
If You remove single space between word. try it
trim(str_replace(' ','','hello word'));
Upvotes: 0
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
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
Reputation: 1319
$cleanStr = trim(preg_replace('/\s\s+/', ' ', str_replace("\n", " ", $str)));
Upvotes: 47
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