去掉多余的空格,但不要去掉两个单词之间的空格


Remove extra spaces but not space between two words

我想删除字符串中存在的额外空格。我试过trim, ltrim, rtrim和其他的,但它们都不起作用,甚至试过下面的东西。

//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); 

有解决办法吗?

更新

: -

输入字符串

: -

"
Hello Welcome
                             to India    "

输出字符串:-

"Hello Welcome to India"
$cleanStr = trim(preg_replace('/'s's+/', ' ', str_replace("'n", " ", $str)));

好的,所以你想从字符串的末尾删除所有的空格和多余的空格。

你可以用一个regex:

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

解释:

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

像这样(例如在Python中,因为我不使用PHP):

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

如果你想删除字符串中的多个空格,你可以使用以下命令:

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

我认为我们在这里应该做的是我们不应该寻找一个空间,我们应该寻找连续的两个空间,然后使它成为一个。这样,它就不会替换文本之间的空格,也不会删除任何其他空格。

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

如果您删除单词之间的单个空格。试试

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

试试这个,这也会删除所有的 

$node3 = htmlentities($node3, null, 'utf-8');
$node3 = str_replace(" ", "", $node3);
$node3 = html_entity_decode($node3);
$node3 = preg_replace('/^'s+|'s+$|'s+(?='s)/', '', $node3);