note 62600 deleted from function.preg-match by colder

From: Date: Mon, 18 Jun 2007 18:29:15 +0000
Subject: note 62600 deleted from function.preg-match by colder
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-127620@lists.php.net to get a copy of this message
Note Submitter: Chris Shucksmith <chris at shucksmith dot com> ---- I created the following snippit to parse fixed width tabular data to an array of arrays. I use this to create a HTML table showing the output from a linux shell command. It requires an array of column widths used to build a regular expression. This is passed to preg_match_all in multiline mode over the entire command line output. $matches is examined and the table built. This example formats a table of SIP Peers connected to an Asterisk VOIP Server. The command output looks like: | # asterisk -rqx 'sip show peers' | Name/username Host Dyn Nat ACL Port Status | 308/308 (Unspecified) D 0 UNKNOWN | 303/303 45.230.86.123 D N 5060 OK (84 ms) | 302/302 192.168.14.71 D 5060 OK (80 ms) | 6 sip peers [3 online , 3 offline] Code: <table> <tr><th></th> <th>Extension</th> <th>Host</th> <th>Dynamic</th> <th>NAT</th><th>ACL</th> <th>Port</th> <th>Status</th> </tr> <?php $dfout = exec("sudo asterisk -rqx 'sip show peers'", $pss); $psline = implode("\\n", $pss); // merge command output with linebreaks $table = array(27,16,4,4,4,9,-1); // table column widths (-1 = all remaining) unset($pattern); foreach($table as $t) { $pattern = ($t == -1) ? $pattern.'(.{0,})' : $pattern.'(.{'.$t.'})'; } $pattern = '/^'.$pattern.'$/m'; // anchor pattern on lines, multiline mode if (preg_match_all($pattern, $psline, $matches,PREG_SET_ORDER)) { unset($matches[0]); // remove first row (column headings) // print_r($matches); // handy to visualise the data structure foreach ($matches as $m) { echo '<tr><td>'; if (strpos($m[7],'OK') !== false) echo '<img src="/img/dg.png">'; if (strpos($m[7],'LAGGED') !== false) echo '<img src="/img/dy.png">'; if (strpos($m[7],'UNKNOWN') !== false) echo '<img src="/img/dr.png">'; echo '</td><td>'.$m[1].'</td><td>'.$m[2].'</td><td>'.$m[3].'</td><td>'; echo $m[4].'</td><td>'.$m[5].'</td><td>'.$m[6].'</td><td>'.$m[7]; echo '</td><tr>'; } } else { echo '<img src="/img/dr.png"> Connection to server returned no data.'; } ?> </table>

« previous php.notes (#127620) next »