Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

PHP Parse Between Tags

Options
  • 22-10-2012 12:12pm
    #1
    Registered Users Posts: 8,004 ✭✭✭


    Just a quick question regarding PHP between tags. I have a HTML style string in this format:
    <td>Number</td>
    <td>Person</td>
    <td>Time</td>

    What I want to do is populate an array based on the info between the td tags. So:
    $array[0] = "Number";
    $array[1] = "Person";

    I know of explode and preg_match but I can't seem to delve between the tags and build an array.

    Many Thanks!


Comments

  • Registered Users Posts: 255 ✭✭boblong


    Have you tried using regular expressions? For example I just wrote this ruby:
    >> a = "<td>Number</td><td>Person</td><td>Time</td>"
    
    >> a.scan(/<td\b[^>]*>(.*?)<\/td>/)
    
     => [["Number"], ["Person"], ["Time"]]
    
    

    That being said, parsing html with regexes is a pretty surefire way to get yourself shouted at, so I'd recommend looking for a php html parser. http://www.codinghorror.com/blog/2009/11/parsing-html-the-cthulhu-way.html


  • Closed Accounts Posts: 19,777 ✭✭✭✭The Corinthian


    [PHP]header("Content-type: text/plain");
    print_r (parseTableData("<td>Number</td><td>Person</td><td>Time</td>"));

    function parseTableData($table) {
    $result = array();
    while (stristr($table, "<td>")) {
    $start = strlen($table) - strlen(stristr($table, "<td>"));
    $table = substr ($table, $start + 4);
    $end = strlen($table) - strlen(stristr($table, "</td>"));
    $result[] = trim(substr($table, 0, $end));
    }
    return $result;
    }[/PHP]
    Note: Comes with no warranty or QA. Naturally would require further complexity in practice as it also presumes table rows with no attributes.


Advertisement