Page 1 of 1

Parsing simple data field

Posted: Tue Mar 20, 2007 3:27 pm
by alex.barylski
So far I have this regex constructed:

Code: Select all

$line = 'NAME(23): John Smith';
  $data = preg_split('/NAME(\(d\))*: (.)+/', $line, -1, PREG_SPLIT_OFFSET_CAPTURE);
The (23) is optional and may *not* always be in existence whereas the the name is always there...

I need the output to always be two array elements:

Code: Select all

$data[0] = 23; // Optional number may not exist but this field should always be set NULL or not
$data[1] = "John Smith"
Is this possible, what am i doing wrong in the regex? Am I passing the wrong constant?

Thanks :)

Posted: Tue Mar 20, 2007 3:38 pm
by feyd
First problem: using preg_split.

preg_match() is what you need.

Code: Select all

[feyd@home]>php -r "$line = 'NAME(23): John Smith'; preg_match('#^NAME(?:\((\d+)\))?:\s*(.*?)\s*$#m', $line, $match); var_dump($match);"
array(3) {
  [0]=>
  string(20) "NAME(23): John Smith"
  [1]=>
  string(2) "23"
  [2]=>
  string(10) "John Smith"
}