根据第一个字符取消设置数组元素

发布于 2024-11-13 18:26:44 字数 308 浏览 5 评论 0原文

我试图找到一种方法来取消设置元素,如果第一个字符是某个字母,在本例中是字母 D...我不确定是否有一个数组函数可以执行此类操作,或者是否有 preg 替换会成功吗?

[0] => Aaron [1] => Bob [2] => Carl [3] => Dale [4] => Devin [5] => Dylan

取消设置所有以字母“D”开头的单词将导致:

[0] => Aaron [1] => Bob [2] => Carl

Im trying to find a way to unset an element if the first character is a certain letter, in this case the letter D... I'm not sure if there is an array function to do something of the sort or if a preg replace would do the trick?

[0] => Aaron [1] => Bob [2] => Carl [3] => Dale [4] => Devin [5] => Dylan

Unset all words that start with letter "D" Would result in:

[0] => Aaron [1] => Bob [2] => Carl

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

街角卖回忆 2024-11-20 18:26:44

手动循环已经完成了任务。但作为单行选项:

 $array = preg_grep('/^(?!D)/', $array);

A manual loop accomplishes the task already. But as one-liner option:

 $array = preg_grep('/^(?!D)/', $array);
坦然微笑 2024-11-20 18:26:44

您可以使用 array_filter 函数:

function filter_firstchar($var){
    return $var[0] != 'D';
}

$result = array_filter($arr, 'filter_firstchar');

如果您要使用的字母过滤方式将会改变,你可以构建一个非常基本的过滤类:

class Filter_FirstChar {
    private $char;
    function __construct($char){
        $this->char = $char;
    }
    function filter($var){
        return $var[0] != $this->char;
    }
}

$result = array_filter($arr, array(new Filter_FirstChar('A'), 'filter'));

You could use the array_filter function:

function filter_firstchar($var){
    return $var[0] != 'D';
}

$result = array_filter($arr, 'filter_firstchar');

If the letter you are going to be filtering by is going to change, you can build a really basic filtering class:

class Filter_FirstChar {
    private $char;
    function __construct($char){
        $this->char = $char;
    }
    function filter($var){
        return $var[0] != $this->char;
    }
}

$result = array_filter($arr, array(new Filter_FirstChar('A'), 'filter'));
吻风 2024-11-20 18:26:44
$i = 0;
$n = count($array);
while ($i < $n) {
  if ($array[$i][0] == 'D')
    unset($array[$i]);
  ++$i;
}
$i = 0;
$n = count($array);
while ($i < $n) {
  if ($array[$i][0] == 'D')
    unset($array[$i]);
  ++$i;
}
就此别过 2024-11-20 18:26:44
foreach($array as $key => $name)
{
    if(substr($name,0,1) == "D")
    {
        unset($array[$key]);
    }
}

是一种适合您的方法。

foreach($array as $key => $name)
{
    if(substr($name,0,1) == "D")
    {
        unset($array[$key]);
    }
}

Is one method that could work well for you.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文