unset last item of array

前端 未结 6 1162
滥情空心
滥情空心 2020-12-18 20:39

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 thi

相关标签:
6条回答
  • 2020-12-18 21:15

    Use explode instead of preg_split. It is faster. Then you can use array_pop and array_shift to remove an item from the end and beginning of the array. Then, use implode to put the remaining items back together again.

    A better solution would be to use str_pos to find the first and last _ and use substr to 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).

    0 讨论(0)
  • With regex, you can do:

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

    regex:

    ^        : begining of the string
    [^_]+    : 1 or more non _ 
    _        : _
    (.+)     : capture 1 or more characters
    _        : _
    [^_]+    : 1 or more non _
    $        : end of string
    
    0 讨论(0)
  • 2020-12-18 21:18
    array_shift($end); //removes first
    array_pop($end); //removes last
    
    0 讨论(0)
  • 2020-12-18 21:20

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

    unset($status[0]); // removes the first item
    unset($status[count($status) - 1]); // removes the last item
    
    0 讨论(0)
  • 2020-12-18 21:31
    $item[$fieldneedle] = " node_os_disk_danger ";
    $status = preg_split('/_/',$item[$fieldneedle]);
    $status = array_slice($status, 1, -1);
    
    0 讨论(0)
  • 2020-12-18 21:33

    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...

    0 讨论(0)
提交回复
热议问题