Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/278.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 取消设置数组的最后一项_Php_Regex_Arrays - Fatal编程技术网

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

Php 取消设置数组的最后一项,php,regex,arrays,Php,Regex,Arrays,在这段代码中,我尝试取消设置$status数组的第一项和最后一项 取消设置但我尝试将其指针放在$end中的最后一项 没有取消设置为此原因我能做什么? $item[$fieldneedle] = " node_os_disk_danger "; $status = preg_split('/_/',$item[$fieldneedle]); unset($status[0]); $end = & end($status); unset($end); 在本例中,我需要使用os\u disk而不

在这段代码中,我尝试取消设置$status数组的第一项和最后一项
取消设置但我尝试将其指针放在$end中的最后一项
没有取消设置为此原因我能做什么?


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


在本例中,我需要使用
os\u disk
而不是
preg\u split
。它更快。
array_shift($end); //removes first
array_pop($end); //removes last
然后,您可以使用
array\u pop
array\u shift
从数组的末尾和开头删除项目。然后,使用
内爆
将其余项目重新组合在一起


更好的解决方案是使用
str\u pos
查找第一个和最后一个
,并使用
substr
在两者之间复制零件。这将只导致一个sting副本,而不必将字符串转换为数组,修改该字符串,然后将数组合并为字符串。(或者你不需要把它们放在一起吗?结尾的“我需要”操作系统磁盘让我很困惑)。

使用regex,你可以:

$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

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

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

它将替换第一个下划线字符之前(包括该下划线字符)的所有内容,以及最后一个下划线字符之后(包括该下划线字符)的所有内容。漂亮、简单、高效……

您还可以使用unset删除最后一项或任何带有密钥的项

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

但是我现在想知道如何在regexp中从第一个到最后一个进行字符串修剪,你知道吗?@ircmaxcell:不知道,因为regex匹配,在捕获组之后,一个
\uuu
后跟一些非
\u
引用:和来自php.net
unset($status[0]); // removes the first item
unset($status[count($status) - 1]); // removes the last item