首页 > 解决方案 > 如何过滤数组中的值

问题描述

我在这里发布我目前面临的一个问题,我有一个数组,我必须过滤以“!”开头的值 后来算了,我尝试了array_filter但没用我想知道是否有另一种方法来过滤值和以“!”开头的单独值 我正在使用代码发布下面的数组以节省空间

这是我到目前为止所做的代码:

$dat= Array
(
    [0] => Lorem
    [1] => ipsum
    [2] => dolor
    [3] => sit
    [4] => amet,
    [5] => consectetur
    [6] => adipiscing
    [7] => elit.
    [8] => <a
    [9] => class="btn
    [10] => btn-default"
    [11] => href="hash_sys.php?tag=bart">
    [12] => !bart
    [13] => </a>
    [14] => Quisque
    [15] => sapien
    [16] => velit,
    [17] => aliquet
    [18] => eget
    [19] => commodo
    [20] => nec,

    [21] => !qwerty
    [22] => auctor
    [23] => a
    [24] => sapien.
    [25] => Nam
    [26] => eu
    [27] => neque
    [28] => vulputate
    [29] => diam
    [30] => rhoncus
    [31] => faucibus.
    [32] => Curabitur
    [33] => quis
    [34] => varius
    [35] => libero.
    [36] => <a
    [37] => class="btn
    [38] => btn-default"
    [39] => href="hash_sys.php?tag=qwerty">
    [40] => !qwerty
    [41] => </a>
    [42] => Lorem.
)
 foreach($dat as $d){
                    if(strpos($d ,'!') !== FALSE ){
                 $d_p=""; 
            $i=0;
            $tag="";
                     $d2=count($dat);
                     while ($i<$d2) {

                         $d_w=$dat[$i];

                            $regex="/!+([a-zA-z0-9._-]+)/";
                            $regex1="/(?:\s|^)![A-Za-z0-9\-\.\_]+(?:\s|$)/";
                    $d1=preg_match_all($regex, $dat[$i],$output_preg,PREG_PATTERN_ORDER);


                       function check_regex($data){
                           if ($data=="/(?:\s|^)![A-Za-z0-9\-\.\_]+(?:\s|$)/")
                           {
                               return $data;
                           }

                           }


                       $d_p= array_column($dat,$output_preg[0][0],$regex1);

                       $d_f= array_filter($d_p,"check_regex" , ARRAY_FILTER_USE_BOTH);
                   $d_c= array_count_values($d_p);
                   print_r($d_p);
                   foreach ($d_c as $d2) {
                       if ($d2>1 ) {
                           $tag=1;

                       } 
                   }
                   $i++;
                     }

                     if($tag==1){
                        echo 1;
                        exit();
                    } else {
                    echo 0;
                }    
                     }

标签: php

解决方案


我没有阅读你的代码。对于这么小的问题,这只是一个巨大的问题,如果我错过了什么,请原谅我。

我使用 preg_grep 过滤掉!前面的值。
如果你想要一个没有的列表,!你也可以使用array_diff。

$arr = ["!qwerty","sapien", "!Bart", "!qwerty"];

$filtered = preg_grep("/^\!.*$/", $arr);

var_dump($filtered);
var_dump(array_diff($arr, $filtered));

https://3v4l.org/uj4Gb

正则表达式模式将确保值以!使用^ $模式中的开头,然后接受任何内容.*


推荐阅读