$re = '/(?:^(R)\|(\d+)\|\^*([^|]*)\|([^|]*)\|(?:([^|]*)\|)?.*$)|(?:^(P)\|(\d+)\|\|(\d+).*$)/im';
$str = 'P|1||322061||^|||U
O|1||138||||||||||||O
R|1|^^^BE(B)||mmol/L||C||||||20150819144937
R|2|^^^BEecf||mmol/L||C
R|3|^^^Ca++|1.17|mmol/L
R|4|^^^Ca++(7.4)||mmol/L||C
R|5|^^^HCO23-||mmol/L||C
R|6|^^^HCO3std||mmol/L||C
R|7|^^^K+|5.0|mmol/L
R|8|^^^Na+|140|mmol/L
R|9|^^^SO2c||%||C
R|10|^^^TCO2||mmol/L||C
R|11|^^^THbc||g/dL||C
R|12|^^^Temp|37.0|C
';
preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);
// Print the entire match result
var_dump($matches);
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for PHP, please visit: http://php.net/manual/en/ref.pcre.php