Parsing simple data field

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
alex.barylski
DevNet Evangelist
Posts: 6267
Joined: Tue Dec 21, 2004 5:00 pm
Location: Winnipeg

Parsing simple data field

Post 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 :)
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post 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"
}
Post Reply