修剪似乎不适用于PHP

时间:2012-11-25 12:55:56

标签: 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($theKeywords as $key){
  $key = trim($key);
}
echo $theKeywords[2];

然而,在这里,输出是“弹跳”而不是“弹跳”。 trim在这里使用的功能不正确吗?

编辑: 我的原始字符串在“弹跳”之前有两个空格,由于某种原因它不想显示。 我尝试用foreach引用它($ theKeywords as& $ key)但是它引发了一个错误。

4 个答案:

答案 0 :(得分:5)

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

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

答案 1 :(得分:3)

您没有在循环中重写原始数组中的值,您可以使用array_map将其简化为一行,就像这样

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

答案 2 :(得分:1)

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

$theKeywords = explode(", ", $keys);
for($i = 0; $i < count($theKeywords); $i++) {
    $theKeywords[$i] = trim($theKeywords[$i]);
}
echo $theKeywords[2];

答案 3 :(得分:0)

使用闭包的另一种方式:

$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 +

相关问题