tags:

views:

96

answers:

6

I need a regular expression to look for the first N chars on an array until a tab or comma separation is found.

array look like:

array (
  0 => '001,Foo,Bar',
  1 => '0003,Foo,Bar',
  2 => '3000,Foo,Bar',
  3 => '3333433,Foo,Bar',
)

I'm looking for the first N chars, so for instance, pattern to search is 0003, get array index 1...

What would be a good way of doing this?

A: 
/^(.*?)[,\t]/

?

kemp
A: 

This PHP5 code will do a prefix search on the first element, expecting a trailing comma. It's O(n), linear, inefficient, slow, etc. You'll need a better data structure if you want better search speed.


<?php
function searchPrefix(array $a, $needle) {
    $expression = '/^' . quotemeta($needle) . ',/';
    $results = array();

    foreach ($a as $k => $v) 
        if (preg_match($expression, $v)) $results[] = $k;

    return $results;
}   

print_r(searchPrefix($a, '0003'));
Pestilence
+1  A: 

Try the regular expression /^0003,/ together with preg_grep:

$array = array('001,Foo,Bar', '0003,Foo,Bar', '3000,Foo,Bar', '3333433,Foo,Bar');
$matches = preg_grep('/^0003,/', $array);
var_dump($matches);
Gumbo
+1 for preg_grep. Better than foreach.
Pestilence
A: 

A REGEXP replacement would be: strpos() and substr()

Following your edit:

Use trim(), after searching for a comma with strpos() and retrieving the required string with substr().

Dor
A: 

use preg_split on the string

$length=10;
foreach($arr as $string) {
  list($until_tab,$rest)=preg_split("/[\t,]+/", $string);
  $match=substr($until_tab, $length);
  echo $match; 
}

or

array_walk($arr, create_function('&$v', 'list($v,$rest) = preg_split("/[\t,]+/", $string);'); //syntax not checked
dnagirl
A: 
$pattern = '/^[0-9]/siU';

for($i=0;$i<count($yourarray);$i++)
{
   $ids = $yourarray[$i];
  if(preg_match($pattern,$ids))
  {
    $results[$i] =  $yourarray[$i];
  }

}
print_r($results);

this will print

  0 =>  '001',
  1 => '0003',
  2 => '3000',
  3 => '3333433'
streetparade