php 从字符串中删除多余的空格
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1703320/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Remove excess whitespace from within a string
提问by joepour
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 excesswhite space from betweenthe strings.
我从数据库查询中收到一个字符串,然后在将其放入 CSV 文件之前删除所有 HTML 标记、回车符和换行符。唯一的问题是,我找不到从字符串之间去除多余空白的方法。
What would be the best way to remove the inner whitespace characters?
删除内部空白字符的最佳方法是什么?
回答by jW.
Not sure exactly what you want but here are two situations:
不确定你想要什么,但这里有两种情况:
If you are just dealing with excess whitespaceon the beginning or end of the string you can use
trim(),ltrim()orrtrim()to remove it.If you are dealing with extra spaces within a string consider a
preg_replaceof multiple whitespaces" "*with a single whitespace" ".
如果您只是处理whitespace字符串开头或结尾的多余内容,则可以使用
trim(),ltrim()或rtrim()将其删除。如果您正在处理字符串中的额外空格,请考虑 a
preg_replaceof multiplewhitespaces" "*和单个whitespace" "。
Example:
例子:
$foo = preg_replace('/\s+/', ' ', $foo);
回答by Cory Dee
$str = str_replace(' ','',$str);
Or, replace with underscore, & nbsp; etc etc.
或者,替换为下划线, 等等等等
回答by d-_-b
$str = trim(preg_replace('/\s+/',' ', $str));
$str = trim(preg_replace('/\s+/',' ', $str));
The above line of code will remove extraspaces, as well as leading and trailing spaces.
上面的代码行将删除额外的空格,以及前导和尾随空格。
回答by Lukas Liesis
none of other examples worked for me, so I've used this one:
没有其他示例对我有用,所以我使用了这个:
trim(preg_replace('/[\t\n\r\s]+/', ' ', $text_to_clean_up))
this replaces all tabs, new lines, double spaces etc to simple 1 space.
这将所有制表符、新行、双空格等替换为简单的 1 个空格。
回答by Apsar
If you want to replace only multiple spaces in a string, for Example: "this string have lots of space . "And you expect the answer to be
"this string have lots of space", you can use the following solution:
如果您只想替换字符串中的多个空格,例如:"this string have lots of space . "并且您希望答案是
"this string have lots of space",您可以使用以下解决方案:
$strng = "this string have lots of space . ";
$strng = trim(preg_replace('/\s+/',' ', $strng));
echo $strng;
回答by Fom
There are security flaws to using preg_replace(), if you get the payload from user input [or other untrusted sources]. PHP executes the regular expression with eval(). If the incoming string isn't properly sanitized, your application risks being subjected to code injection.
如果您从用户输入 [或其他不受信任的来源] 获取有效负载,则使用 preg_replace() 存在安全缺陷。PHP 使用 eval() 执行正则表达式。如果传入的字符串未正确清理,您的应用程序就有遭受代码注入的风险。
In my own application, instead of bothering sanitizing the input (and as I only deal with short strings), I instead made a slightly more processor intensive function, though which is secure, since it doesn't eval() anything.
在我自己的应用程序中,我没有费心清理输入(并且因为我只处理短字符串),而是创建了一个处理器密集型函数,尽管这是安全的,因为它不 eval() 任何东西。
function secureRip(string $str): string { /* Rips all whitespace securely. */
$arr = str_split($str, 1);
$retStr = '';
foreach ($arr as $char) {
$retStr .= trim($char);
}
return $retStr;
}
回答by Sandip Layek
$str = preg_replace('/[\s]+/', ' ', $str);
回答by Amir Fo
You can use:
您可以使用:
$str = trim(str_replace(" ", " ", $str));
This removes extra whitespaces from both sidesof string and converts two spaces to onewithin the string. Note that this won't convert three or more spaces in a row to one! Another way I can suggest is using implode and explode that is safer but totally not optimum!
这会从字符串的两侧删除多余的空格,并将字符串中的两个空格转换为一个。请注意,这不会将一行中的三个或更多空格转换为一个!我建议的另一种方法是使用内爆和爆炸,这更安全但完全不是最佳选择!
$str = implode(" ", array_filter(explode(" ", $str)));
My suggestion is using a native for loop or using regex to do this kind of job.
我的建议是使用本机 for 循环或使用正则表达式来完成此类工作。
回答by JScarry
To expand on Sandip's answer, I had a bunch of strings showing up in the logs that were mis-coded in bit.ly. They meant to code just the URL but put a twitter handle and some other stuff after a space. It looked like this
为了扩展 Sandip 的答案,我在日志中显示了一堆在 bit.ly 中编码错误的字符串。他们打算只对 URL 进行编码,但在空格后放了一个 twitter 句柄和其他一些东西。它看起来像这样
? productID =26%20via%20@LFS
Normally, that would‘t be a problem, but I'm getting a lot of SQL injection attempts, so I redirect anything that isn't a valid ID to a 404. I used the preg_replace method to make the invalid productID string into a valid productID.
通常,这不会有问题,但是我收到了很多 SQL 注入尝试,因此我将任何不是有效 ID 的内容重定向到 404。我使用 preg_replace 方法将无效的 productID 字符串转换为有效的产品 ID。
$productID=preg_replace('/[\s]+.*/','',$productID);
I look for a space in the URL and then remove everything after it.
我在 URL 中查找一个空格,然后删除它后面的所有内容。
回答by Shahbaz Khan
$str = "I am a PHP Developer";
$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);

