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

时间:2014-07-04 09:14:02

标签: php regex

我想删除字符串中的额外空格。我尝试了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"

6 个答案:

答案 0 :(得分:24)

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

答案 1 :(得分:7)

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

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

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

答案 2 :(得分:3)

如果要删除字符串中的多个空格,可以使用以下内容:

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

答案 3 :(得分:1)

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

  

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

了解Str Replace

的更多信息

答案 4 :(得分:0)

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

if (variable == something) { label.text = "something"; } else if (variable == somethingelse) { label.text = "somethingelse"; }

答案 5 :(得分:0)

试试这个,这也会删除所有&amp; 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);
相关问题