删除多余的空格,但不要删除两个单词之间的空格

2022-08-30 20:20:48

我想删除字符串中存在的多余空格。我已经尝试过,和其他人,但不是他们工作,甚至尝试了以下的东西。trimltrimrtrim

//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"

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

答案 2

好的,所以你想从字符串的末尾修剪所有空格和单词之间的多余空格。

您可以使用单个正则表达式执行此操作:

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

推荐