phphtmlhtml-parsingtablerow

Separate a string containing multiple sets of <tr> tags into an array


I have a string variable that contains 3 trs:

$string = '<tr><td> Total 1 </td><td>779,00</td></tr><tr><td> Total 2 </td><td>867,25</td></tr><tr><td> Total 3 </td><td>939,00</td></tr>';

I try to split the string to get 3 <tr>...</tr> Tags.

I have tried :

$match = preg_split('[(<tr[^>]*>.*?</tr>)]', $string , NULL, PREG_SPLIT_DELIM_CAPTURE);

but I don't get good results.


Solution

  • I don't recommend using regex to parse your HTML, but if you want to anyways, here is the correct way of doing it:

     $regexPattern = "/<tr>(.*?)<\\/tr>/"; 
     $string = "<tr><td> Total 1 </td><td>779,00</td></tr><tr><td> Total 2 </td><td>867,25</td></tr><tr><td> Total 3 </td><td>939,00</td></tr>"; 
    
     preg_match_all($regexPattern , $string , $matches);
    

    As requested, here is the regex to include the tags:

     $regexPattern = "/(<tr>.*?<\\/tr>)/"; 
    

    Good luck.