取消数组的最后一个元素

19
在这段代码中,我尝试取消设置 $status 数组的第一个和最后一个项目。但是,当我试图将它们的指针放在 $end 中时,无法取消设置最后一个项目。为了解决这个问题,我应该怎么做?

$item[$fieldneedle] = " node_os_disk_danger ";
$status = preg_split('/_/',$item[$fieldneedle]);
unset($status[0]);
$end = & end($status);
unset($end);


在这个例子中,我需要 os_disk

6个回答

67
array_shift($end); //removes first
array_pop($end); //removes last

1
参考资料:http://php.net/manual/en/function.array-pop.php 和 http://php.net/manual/en/function.array-shift.php 来自 php.net - Louis Loudog Trottier

2
使用explode代替preg_split,它更快。然后,您可以使用array_poparray_shift从数组的末尾和开头删除一个项。然后,使用implode将剩余的项目重新组合在一起。
更好的解决方案是使用str_pos查找第一个和最后一个_,并使用substr复制中间部分。这将只导致一个字符串复制,而不必将字符串转换为数组,修改该数组,并将数组组合成字符串。(或者您不需要将它们组合在一起吗?“我需要”os_disk“在结尾处让我感到困惑)。

字符串的主体已经有了,但我想知道如何在正则表达式中从第一个和最后一个字符修剪它。你有什么想法吗? - AmirModiri

1
$item[$fieldneedle] = " node_os_disk_danger ";
$status = preg_split('/_/',$item[$fieldneedle]);
$status = array_slice($status, 1, -1);

1
您可以使用unset来删除最后一个或任何带有键的项目。
unset($status[0]); // removes the first item
unset($status[count($status) - 1]); // removes the last item

1

如果你想要结果是一个字符串,为什么还要将其转换为字符串呢?

$regex = '#^[^_]*_(.*?)_[^_]*$#';
$string = preg_replace($regex, '\\1', $string);

它替换了第一个下划线字符及其之前的所有内容,以及最后一个下划线字符及其之后的所有内容。很好,简单而高效...


0

使用正则表达式,您可以做到以下事情:

$item[$fieldneedle] = preg_replace("/^[^_]+_(.+)_[^_]+$/", "$1", $item[$fieldneedle]);

正则表达式:

^        : begining of the string
[^_]+    : 1 or more non _ 
_        : _
(.+)     : capture 1 or more characters
_        : _
[^_]+    : 1 or more non _
$        : end of string

@ircmaxcell:不是这样的,因为正则表达式匹配,在捕获组之后,会跟着一个下划线 _,然后是一些非下划线字符。 - Toto

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接