去除多余空格但不去除两个单词之间的空格。

21

我想去掉字符串中多余的空格。我已经尝试过 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
你能提供你的数据吗? - Sadikhasan
1
给出一些你想要完成的例子(起始字符串,目标字符串)。 - clami219
trim应该可以胜任。但是,如果你想使用正则表达式,可以尝试这个^\s*|\s*$ - Faiz Shukri
我可能误解了你的问题。你想让字符串" a b "变成"a b"还是"a b" - Tim Pietzcker
你的字符串中是否包含HTML字符,例如<br />等? - Deepika Janiyani
显示剩余2条评论
6个回答

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

1
完美的,运行良好。谢谢。 - Manoj K

14

好的,所以您想要从字符串末尾修剪所有空格,并删除单词之间多余的空格。

您可以使用一个正则表达式来实现:

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

这似乎无法删除由 创建的空格。 - DragonFire
@DragonFire:如果你将正则表达式应用于源代码,那么是的 - &nbsp; 不是空格,%200x20 也不是。 - Tim Pietzcker

5
如果您想在字符串中删除多个空格,可以使用以下方法:
$testStr = "                  Hello Welcome
                         to India    ";
$ro = trim(preg_replace('/\s+/', ' ', $testStr));

OP 不想删除字符串中除开开头和结尾以外的空格。 - Tim Pietzcker
OP想要移除字符串中间的额外空格。 - VMai
我的更新脚本按要求返回“你好,欢迎来到印度”。 - jamb

3
我认为我们在这里应该不是寻找一个空格,而是要查找连续的两个空格,然后将它们变成一个空格。这样就不会替换文本之间的空格,并且还可以去除其他任何空格。
以下是相应的代码:

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

更多关于Str Replace的信息,请访问链接。

0

试试这个,它也会删除所有的&nbsp

$node3 = htmlentities($node3, null, 'utf-8');
$node3 = str_replace("&nbsp;", "", $node3);
$node3 = html_entity_decode($node3);

$node3 = preg_replace('/^\s+|\s+$|\s+(?=\s)/', '', $node3);

0

如果您想去掉单词之间的空格,请尝试以下代码:

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接