0

hi I have array of elements containing pattern like $arr = array ('0/' ,'0/12/3','1/2') i need to have array of "0/" elements i've tried to use command

arr_with_zero_slash = preg_grep('@$[0-9]/$@',$arr)

but function works only witch pattern like 1/ , 2/ and so one. This is because 0/ is treated as special sign but i dont know how to deal with that. Any ideas?

Adam Krawczyk
  • 71
  • 1
  • 5
  • 1
    *"0/ is treated as special sign"* -- there is nothing special with `0/` – axiac Feb 13 '18 at 12:30
  • fyi, that "command" is not valid PHP code. Also, `[0-9]` is getting you all numbers from 0 to 9, you only want 0, right? – brombeer Feb 13 '18 at 12:33

2 Answers2

1

I think this is what you mean: Cycle through array $arr using a foreach-loop, and unset (remove) all elements that don't start with '0/'...

$arr = array ('0/' ,'0/12/3','1/2');
foreach($arr as $key=>$value){
  if(substr($value,0,2)<>"0/"){
    unset($arr[$key]);
  }
}

With:

$arr = array ('0/' ,'0/12/3','1/2') 

this will be the outcome:

array(2) { [0]=> string(2) "0/" [1]=> string(6) "0/12/3" }
Werner
  • 449
  • 4
  • 12
1

If you want to get all elements starting with 0/ try this:

<?php
$arr = array ('0/' ,'0/12/3','1/2', '1/0/4');
$arr_with_zero_slash = preg_grep('@^0/@',$arr);
print_r($arr_with_zero_slash);

This will output

Array (
    [0] => 0/
    [1] => 0/12/3
)

Removed the first $ since it's a meta-character.

Changed [0-9] to 0, since you only want 0/ and not 1/, 2/ etc.

Removed the second $ since you also want 0/12/3.

brombeer
  • 8,716
  • 5
  • 21
  • 27