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
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'