I agree with Andreas about using preg_match_all()
, but not with his pattern.
For stability, I recommend consuming the entire string from the beginning.
- Match the label and its trailing colon.
[^:]+:
- Match zero or more spaces.
\s*
- Forget what you matched so far
\K
- Lazily match zero or more characters (giving back when possible -- make minimal match).
.*?
- "Look Ahead" and demand that the matched characters from #4 are immediately followed by a comma, then 1 or more non-comma&non-colon character (the next label), then a colon
,[^,:]+:
OR the end of the string $
.
Code: (Demo)
$line = "Type:Bid, End Time: 12/20/2018 08:10 AM (PST), Price: $8,000,Bids: 14, Age: 0, Description: , Views: 120270, Valuation: $10,75, IsTrue: false";
var_export(
preg_match_all(
'/[^:]+:\s*\K.*?(?=\s*(?:$|,[^,:]+:))/',
$line,
$out
)
? $out[0] // isolate fullstring matches
: [] // no matches
);
Output:
array (
0 => 'Bid',
1 => '12/20/2018 08:10 AM (PST)',
2 => '$8,000',
3 => '14',
4 => '0',
5 => '',
6 => '120270',
7 => '$10,75',
8 => 'false',
)