Removing more than one white-space

坚强是说给别人听的谎言 提交于 2019-12-22 03:49:15

问题


So, If I have a string like

"hello    what is  my    name"

How can I take all of the spaces and replace each with only one space?


回答1:


This should do it:

$replaced = preg_replace('/\s\s+/', ' ', $text);

Output:

hello what is my name



回答2:


Found the solution:

<?php

$str = ' This is    a    test   ';
$count = 1;
while($count)
    $str = str_replace('  ', ' ', $str, $count);

?>



回答3:


Try this:-

$desc = "hello    what is  my    name";
echo trim(preg_replace('/\s+/', ' ', $desc));



回答4:


You can use trim(), So in your case

$result = trim('hello    what is  my    name');
echo $result;

it will output like this

hello what is my name

As of this PHP Manual Ref :

This function returns a string with whitespace stripped from the beginning and end of str. Without the second parameter, trim() will strip these characters:

  • " " (ASCII 32 (0x20)), an ordinary space.
  • "\t" (ASCII 9 (0x09)), a tab.
  • "\n" (ASCII 10 (0x0A)), a new line (line feed).
  • "\r" (ASCII 13 (0x0D)), a carriage return.
  • "\0" (ASCII 0 (0x00)), the NUL-byte.
  • "\x0B" (ASCII 11 (0x0B)), a vertical tab.


来源:https://stackoverflow.com/questions/2887023/removing-more-than-one-white-space

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!