问题
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