简体   繁体   English

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

[英]Remove extra spaces but not space between two words

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 tried the below stuffs. 我尝试了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); 

Is there any solution for this ? 有什么解决办法吗?

Updated:- 更新:-

Input String:- 输入字符串:

"
Hello Welcome
                             to India    "

Output String:- 输出字符串:-

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

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): 像这样(Python中的示例,因为我不使用PHP):

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

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. 我认为我们应该在此处执行的操作是,我们不应该寻找1个空间,而应该寻找连续的两个空间,然后使其变成一个。 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 有关Str Replace的更多信息

If You remove single space between word. 如果删除单词之间的单个空格。 try it 试试吧

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

Try this, this will also remove all &nbsp 试试这个,这也会删除所有&nbsp

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM