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 trie
If You remove single space between word. try it
trim(str_replace(' ','','hello word'));
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'
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);
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));
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
$cleanStr = trim(preg_replace('/\s\s+/', ' ', str_replace("\n", " ", $str)));