我要从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
,只会删除单个空格。有人能告诉我怎么做吗?
发布于 2010-02-24 21:03:40
您需要:
$ro = preg_replace('/\s+/', ' ', $row['message']);
您正在使用\s\s+
,它表示空格(空格、制表符或换行符)后跟一个或多个空格。这实际上意味着用一个空格替换两个或多个空格。
您想要的是用单个空格替换一个或多个空格,这样您就可以使用模式\s\s*
或\s+
(推荐)
发布于 2010-02-24 21:21:18
<?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 is a string with
spaces, tabs and newlines present
---
This is a string with spaces, tabs and newlines present
发布于 2012-08-20 00:12:18
preg_replace('/[\s]+/mu', ' ', $var);
\s
已经包含了制表符和新行,所以上面的正则表达式似乎就足够了。
https://stackoverflow.com/questions/2326125
复制相似问题