从字符串中删除多余的空格 [英] Remove excess whitespace from within a string
问题描述
我从数据库查询中接收到一个字符串,然后在将其放入CSV文件之前,删除了所有HTML标记,回车符和换行符.唯一的是,我找不到从字符串之间的 中删除多余空白的方法.
I receive a string from a database query, then I remove all HTML tags, carriage returns and newlines before I put it in a CSV file. Only thing is, I can't find a way to remove the excess white space from between the strings.
删除内部空白字符的最佳方法是什么?
What would be the best way to remove the inner whitespace characters?
推荐答案
不确定确切要做什么,但有两种情况:
Not sure exactly what you want but here are two situations:
-
如果仅在字符串的开头或结尾处理多余的空格,则可以使用
trim()
,ltrim()
或rtrim()
删除它.
If you are just dealing with excess whitespace on the beginning or end of the string you can use
trim()
,ltrim()
orrtrim()
to remove it.
如果要处理字符串中的多余空格,请考虑由多个空格 " "*
和一个空格 " "
组成的preg_replace
. /p>
If you are dealing with extra spaces within a string consider a preg_replace
of multiple whitespaces " "*
with a single whitespace " "
.
示例:
$foo = preg_replace('/\s+/', ' ', $foo);
这篇关于从字符串中删除多余的空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!