如何使用 PHP 从数组中去除空格?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3384058/
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
How do you strip whitespace from an array using PHP?
提问by ota
I was wondering how can I strip white space from an array using PHP?
我想知道如何使用 PHP 从数组中去除空白?
回答by Gordon
You can use a combination of
您可以使用以下组合
array_filter— Filters elements of an array using a callback functionarray_map— Applies the callback to the elements of the given arraystrim— Strip whitespace (or other characters) from the beginning and end of a string
Code:
代码:
array_filter(array_map('trim', $array));
This will remove all whitespace from the sides (but not between chars). And it will remove any entries of input equal to FALSE(e.g. 0, 0.00, null, false, …)
这将删除两侧的所有空格(但不会删除字符之间)。它将删除任何等于 FALSE的输入条目(例如 0, 0.00, null, false, ...)
Example:
例子:
$array = array(' foo ', 'bar ', ' baz', ' ', '', 'foo bar');
$array = array_filter(array_map('trim', $array));
print_r($array);
// Output
Array
(
[0] => foo
[1] => bar
[2] => baz
[5] => foo bar
)
回答by Anax
Your question isn't very clear, so I will try to cover almost all cases.
您的问题不是很清楚,因此我将尝试涵盖几乎所有情况。
In general, you need to create a function which will do what you need, be it removing the spaces from the left and right of each element or remove the whitespace characters completely. Here's how:
通常,您需要创建一个函数来满足您的需求,无论是删除每个元素左右两侧的空格还是完全删除空格字符。就是这样:
<?php
function stripper($element)
{
return trim($element); // this will remove the whitespace
// from the beginning and the end
// of the element
}
$myarray = array(" apple", "orange ", " banana ");
$stripped = array_map("stripper", $myarray);
var_dump($stripped);
?>
Result:
Array
(
[0] => "apple"
[1] => "orange"
[2] => "banana"
)
You can take it from here.
你可以从这里拿走。
回答by Imran Tahir Khattak
$subject = $_REQUEST['jform']['name_cat'];
$input = str_replace(" ","",$subject);

