PHP从数组中删除最后一个单词

时间:2012-02-22 07:53:12

标签: php arrays

我在以下格式的数组中进行mysql查询,我要删除最后一个和

Array ( [0] => date = '2012-02-22' and time ='08:49' and  [1] => date = '2012-02-22' and time ='08:49' and )

在将此数组放入此函数array_values();

后,我将此数组作为输出

我试过rtim并修剪。

非常感谢

4 个答案:

答案 0 :(得分:2)

尝试以下方法,

array_push(yourarray, rtrim(array_pop(yourarray), ' and'));

它将弹出最后一个元素,在末尾修剪“和”,然后将修改后的元素重新添加到数组中。

例如,

$yourarray = array("date = '2012-02-22' and time ='08:49' and",  
             "date = '2012-02-22' and time ='08:49' and ");

var_dump($yourarray);
array_push($yourarray, rtrim(array_pop($yourarray), ' and'));
var_dump($yourarray);

输出以下内容

array(2) {
  [0]=>
  string(41) "date = '2012-02-22' and time ='08:49' and"
  [1]=>
  string(42) "date = '2012-02-22' and time ='08:49' and "
}

array(2) {
  [0]=>
  string(41) "date = '2012-02-22' and time ='08:49' and"
  [1]=>
  string(37) "date = '2012-02-22' and time ='08:49'"
}

所以,最后一个元素中的最后一个“和”已被删除。

答案 1 :(得分:0)

$arr = array_map("remove_last_and", $arr);
function remove_last_and($el) {
    return preg_replace('/\s*and\s*$/i', '', $el);
}

示例:

$arr = array("date = '2012-02-22' and time ='08:49' and",  
             "date = '2012-02-22' and time ='08:49' and ");
$arr = array_map("remove_last_and", $arr);
function remove_last_and($el) {
    return preg_replace('/\s*and\s*$/i', '', $el);
}
var_dump($arr);

输出:

array(2) {
  [0]=>
  string(37) "date = '2012-02-22' and time ='08:49'"
  [1]=>
  string(37) "date = '2012-02-22' and time ='08:49'"
}

ps:我没有编写内联或匿名函数,因为我不知道您使用的是哪个版本的PHP。但是,作为示例,您可以从php 5.3开始编写

$arr = array_map(function($el) {
            return preg_replace('/\s*and\s*$/i', '', $el);
       }, $arr);

ps:我不认为使用trimrtrim是好的,因为如果查询略有不同并且'和'字母接近结尾,它可以删除查询的一部分字符串。

答案 2 :(得分:0)

$a = array ( 0 => "date = '2012-02-22' and time ='08:49' **and**",  1 => "date = '2012-02-22' and time ='08:49' **and**");

function func($v){
    return rtrim($v,' **and**');
}
$b = array_map('func',$a);

答案 3 :(得分:0)

使用trim()和可选参数'和'

foreach($myarray as $element)
{
  trim($element, 'and')
}

编辑:仅移除最后一个元素中的最后一个“和”

 trim($myarray[count($myarray) -1] , 'and')