Php 修剪不';好像不行

Php 修剪不';好像不行,php,Php,我非常喜欢PHP中的函数trim。然而,我想我遇到了一个奇怪的障碍。我有一个名为keys的字符串,其中包含:“mavrick、ball、bouncing、food、easy mac”,并执行此函数 // note the double space before "bouncing" $keys = "mavrick, ball, bouncing, food, easy mac, "; $theKeywords = explode(", ", $keys); foreach($theKeyw


我非常喜欢PHP中的函数
trim
。然而,我想我遇到了一个奇怪的障碍。我有一个名为keys的字符串,其中包含:“mavrick、ball、bouncing、food、easy mac”,并执行此函数

// note the double space before "bouncing"
$keys = "mavrick, ball,  bouncing, food,  easy mac, ";
$theKeywords = explode(", ", $keys);
foreach($theKeywords as $key){
  $key = trim($key);
}
echo $theKeywords[2];
然而,这里的输出是“反弹”而不是“反弹”。
trim
不是这里使用的正确功能吗

编辑:
我原来的字符串在“bounce”之前有两个空格,出于某种原因,它不想出现。
我试着用foreach($theKeywords as&$key)引用它,但它抛出了一个错误。

问题是您使用的是副本,而不是原始值。请改用引用:

$theKeywords = explode(", ", $keys);
foreach($theKeywords as &$key){
  $key = trim($key);
}
echo $theKeywords[2];

$key
获取值的副本,而不是实际值。要更新实际值,请在数组本身中修改它(例如,使用
for
循环):

$theKeywords=explode(“,”,$keys);
对于($i=0;$i
如果没有在循环的原始数组中重新写入值,可以使用
数组映射将其简化为一行,如下所示

$theKeywords = array_map('trim', explode(',', $keys));

使用闭包的另一种方法:

$keys = "mavrick, ball,  bouncing, food,  easy mac, ";
$theKeywords = explode(", ", $keys);
array_walk($theKeywords, function (&$item, $key) {
    $item = trim($item);
});
print $theKeywords[2];

但是,它只适用于PHP 5.3+

那么,如果您使用trim()为什么要用“,”而不是“,”?
code
Parse error:Parse error,unexpected'&',在chooseCats.PHP的第40行
code
也不要忘记取消设置($key)
在循环之后,避免以后使用同一变量时出现问题。@Maerlyn谢谢你的提示,我还不知道。我希望$key在该范围内是有效的。我在chooseCats.php的第40行“code”错误上得到了一个“Parse error:Parse error,unexpected”和“T_VARIABLE”或“$”,尽管…@rekire它是有效的,但它仍然保留了对您数据库中最后一项的引用array@rekire就像JavaScript一样,PHP只有变量的全局和函数作用域。PHP中没有块级别的作用域。参考:+1非常简洁-不超过或不低于它所需要的:)
$keys = "mavrick, ball,  bouncing, food,  easy mac, ";
$theKeywords = explode(", ", $keys);
array_walk($theKeywords, function (&$item, $key) {
    $item = trim($item);
});
print $theKeywords[2];