Advertisement
Help Keep Boards Alive. Support us by going ad free today. See here: https://subscriptions.boards.ie/.
If we do not hit our goal we will be forced to close the site.

Current status: https://keepboardsalive.com/

Annual subs are best for most impact. If you are still undecided on going Ad Free - you can also donate using the Paypal Donate option. All contribution helps. Thank you.
https://www.boards.ie/group/1878-subscribers-forum

Private Group for paid up members of Boards.ie. Join the club.

PHP Parse Between Tags

  • 22-10-2012 12:12PM
    #1
    Registered Users, Registered Users 2 Posts: 7,994 ✭✭✭


    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, Registered Users 2 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