html - PHP Preg Matching Capture Groups -


this question has answer here:

i can't seem hang of regular expressions in php. specifically, group capturing part.

i have string looks this

<table cellpadding="0" cellspacing="0" border="0" width="100%" class="list">    <tr class='row_type_1'>     <td class="time">                       3:45 pm     </td>     <td class="name">                       kira     </td>   </tr>    <tr class='row_type_2'>     <td class="time">                       4:00 pm     </td>     <td class="name">                       near     </td>   </tr>  </table> 

and want array this

array (    [0] => array    (       [0] => 3:45 pm       [1] => kira    )    [1] => array    (       [0] => 4:00 pm       [1] => near    ) ) 

i want use preg_match, , not explode, array_keys or loops. took me while figure out needed /s .* count line breaks; i'm eager see pattern , capture syntax.

edit: pattern need (row_type_1|row_type_2) capture 2 types of row in table want data from. example, after row_type_2 came row_type_3, followed row_type_1, row_type_3 ignored , array add data row_type_1 have below.

array (    [0] => array    (       [0] => 3:45 pm       [1] => kira    )    [1] => array    (       [0] => 4:00 pm       [1] => near    )    [2] => array    (       [0] => 5:00 pm       [1] => l    ) ) 

i use xpath , dom retrieve information html. using regexes can messy if html or query more complex. (as see). , dom , xpath standards this. why not using it?

imagine code example:

// load html dom tree $doc = new domdocument(); $doc->loadhtml($html);  // create xpath selector $selector  = new domxpath($doc);  // grab results $result = array(); // select tr class starts 'row_type_' foreach($selector->query('//tr[starts-with(@class, "row_type_")]') $tr) {     $record = array();     // select value of inner td nodes     foreach($selector->query('td[@class="time"]', $tr) $td) {         $record[0]= trim($td->nodevalue);     }     foreach($selector->query('td[@class="name"]', $tr) $td) {         $record[1]= trim($td->nodevalue);     }     $result []= $record; }  var_dump($result); 

Comments

Popular posts from this blog

node.js - Bad Request - node js ajax post -

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -