php 取消设置数组的最后一项

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4668997/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 13:55:33  来源:igfitidea点击:

unset last item of array

phpregexarrays

提问by AmirModiri

in this code i try to unset first and last item of $status array
to unset but the last item that i tried place thier pointer in $end
not unset what can I do for this reason?

在这段代码中,我尝试取消设置 $status 数组的第一项和最后一项
以取消设置,但我尝试将其指针放在 $end 中的最后一项
没有取消设置,出于这个原因我该怎么办?


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


in this example i need os_disk


在这个例子中我需要 os_disk

回答by Diablo

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

回答by GolezTrol

Use explodeinstead of preg_split. It is faster. Then you can use array_popand array_shiftto remove an item from the end and beginning of the array. Then, use implodeto put the remaining items back together again.

使用explode代替preg_split。它更快。然后您可以使用array_poparray_shift从数组的末尾和开头删除一个项目。然后,使用implode将剩余的物品重新组合在一起。

A better solution would be to use str_posto find the first and last _and use substrto copy the part inbetween. This will cause only one sting copy, instead of having to transform a string to array, modify that, and put the array together into a string. (Or don't you need to put them together? The 'I need 'os_disk' at the end confuses me).

更好的解决方案是使用str_pos查找第一个和最后一个_并使用substr复制中间的部分。这将只导致一个 sting 副本,而不必将字符串转换为数组,修改它,然后将数组组合成一个字符串。(或者你不需要把它们放在一起吗?最后的'我需要'os_disk'让我感到困惑)。

回答by Savetheinternet

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

回答by ircmaxell

Well, if you want the result to be a string, why bother converting to a string?

好吧,如果你希望结果是一个字符串,为什么还要转换成一个字符串呢?

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

It replaces everything up to and including the first underscore character, and everything after and including the last underscore character. Nice, easy and efficient...

它替换包括第一个下划线字符在内的所有内容,以及最后一个下划线字符之后和包括的所有内容。漂亮,简单,高效...

回答by Priyank

You can also use unset to remove last or any item with key

您还可以使用 unset 删除最后一个或任何带有键的项目

unset($status[0]); // removes the first item
unset($status[count($status) - 1]); // removes the last item

回答by Toto

With regex, you can do:

使用正则表达式,您可以:

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

regex:

正则表达式:

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