Remove multiple whitespaces

2019-01-02 22:15发布

I'm getting $row['message'] from a MySQL database and I need to remove all whitespace like \n \t and so on.

$row['message'] = "This is   a Text \n and so on \t     Text text.";

should be formatted to:

$row['message'] = 'This is a Text and so on Text text.';

I tried:

 $ro = preg_replace('/\s\s+/', ' ',$row['message']);
 echo $ro;

but it doesn't remove \n or \t, just single spaces. Can anyone tell me how to do that?

15条回答
小情绪 Triste *
2楼-- · 2019-01-02 22:43

You need:

$ro = preg_replace('/\s+/', ' ',$row['message']);

You are using \s\s+ which means whitespace(space, tab or newline) followed by one or more whitespace. Which effectively means replace two or more whitespace with a single space.

What you want is replace one or more whitespace with single whitespace, so you can use the pattern \s\s* or \s+ (recommended)

查看更多
做个烂人
3楼-- · 2019-01-02 22:43
preg_replace('/(\s\s+|\t|\n)/', ' ', $row['message']);

This replaces all tabs, all newlines and all combinations of multiple spaces, tabs and newlines with a single space.

查看更多
劳资没心,怎么记你
4楼-- · 2019-01-02 22:43

This is what I would use:

a. Make sure to use double quotes, for example:

$row['message'] = "This is   a Text \n and so on \t     Text text.";

b. To remove extra whitespace, use:

$ro = preg_replace('/\s+/', ' ', $row['message']); 
echo $ro;

It may not be the fastest solution, but I think it will require the least code, and it should work. I've never used mysql, though, so I may be wrong.

查看更多
唯我独甜
5楼-- · 2019-01-02 22:43

this will replace multiple tabs with a single tab

preg_replace("/\s{2,}/", "\t", $string);
查看更多
不美不萌又怎样
6楼-- · 2019-01-02 22:44
<?php
$str = "This is  a string       with
spaces, tabs and newlines present";

$stripped = preg_replace(array('/\s{2,}/', '/[\t\n]/'), ' ', $str);

echo $str;
echo "\n---\n";
echo "$stripped";
?>

This outputs

This is  a string   with
spaces, tabs and newlines present
---
This is a string with spaces, tabs and newlines present
查看更多
戒情不戒烟
7楼-- · 2019-01-02 22:44

Without preg_replace, with the help of loop.

<?php

$str = "This is   a Text \n and so on \t     Text text.";
$str_length = strlen($str);
$str_arr = str_split($str);
for ($i = 0; $i < $str_length; $i++) {
    if (isset($str_arr[$i + 1])
       && $str_arr[$i] == ' '
       && $str_arr[$i] == $str_arr[$i + 1]) {
       unset($str_arr[$i]);
    } 
    else {
      continue;
    }
}

 echo implode("", $str_arr) ; 

 ?>
查看更多
登录 后发表回答