删除多个空格

新手上路,请多包涵

我正在从 MySQL 数据库中获取 $row['message'] 并且我需要删除所有空格,例如 \n \t 等等。

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

应格式化为:

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

我试过了:

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

但它不会删除 \n\t ,只是单个空格。谁能告诉我该怎么做?

原文由 creativz 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 332
1 个回答

简化为一个功能:

 function removeWhiteSpace($text)
{
    $text = preg_replace('/[\t\n\r\0\x0B]/', '', $text);
    $text = preg_replace('/([\s])\1+/', ' ', $text);
    $text = trim($text);
    return $text;
}

基于丹尼尔奥尼尔的回答。

原文由 Lukas Liesis 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题