我正在此处发布当前遇到的问题,我有一个数组,其中必须过滤以“!”开头的值然后算了一下,我尝试了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;
}
}
答案 0 :(得分:1)
我没有阅读您的代码。这样一个小问题真是太过庞大了,如果我错过了什么,请原谅我。
我使用preg_grep过滤掉前面带有!
的值。
如果您随后想要不带!
的所有列表,则可以使用array_diff。
$arr = ["!qwerty","sapien", "!Bart", "!qwerty"];
$filtered = preg_grep("/^\!.*$/", $arr);
var_dump($filtered);
var_dump(array_diff($arr, $filtered));
通过使用模式中的!
,正则表达式模式将确保值以^ $
开头,然后.*
接受任何内容
答案 1 :(得分:1)
我了解的是:
这是我的工作代码
$dat= Array("Lorem","ipsum","dolor","sit","amet,","consectetur","adipiscing","elit.","<a","class="btn"," btn-default""," href="hash_sys.php?tag=bart">"," !bart"," </a>"," Quisque"," sapien"," velit,"," aliquet"," eget"," commodo"," nec,",
" !qwerty"," auctor"," a"," sapien."," Nam"," eu"," neque"," vulputate"," diam"," rhoncus"," faucibus."," Curabitur"," quis"," varius"," libero."," <a"," class="btn"," btn-default""," href="hash_sys.php?tag=qwerty">"," !qwerty"," </a>"," Lorem.",
);
$filter = array();
foreach($dat as $d){
if(substr($d,0,1) !== "!")
$filter[] = $d;
}
echo "<h3>Original</h3>";
echo "<pre>"; var_dump($dat); echo "</pre>";
echo "<h3>Filtered</h3>";
echo "<pre>"; var_dump($filter); echo "</pre>";
echo "<h3>Count Difference</h3>";
echo "<pre>"; var_dump(sizeof($dat) - sizeof($filter)); echo "</pre>";
substr检查我字符串的第一个元素是否为!
如果不是以!开头添加到过滤器数组中的
过滤后的元素是dat和filter的大小相减