Page 1 of 1

Using preg_replace - HTML parse.

Posted: Thu Jun 05, 2008 5:11 am
by Peec
Hi guys.


I have programmed for 3 years and i still dont understand the preg_* functions that well..

I am just wondering if someone could help me out.


Say i got this HTML code:

Code: Select all

 
<html>
<head></head>
<body>
<table>
    <tr>
        <td>Item</td>
        <td>Value</td>
    </tr>
    <tr>
        <td>Boxer shorts</td>
        <td>20USD</td>
    </tr>
    <tr>
        <td>T-shirt</td>
        <td>30USD</td>
    </tr>
    <tr>
        <td>Pants</td>
        <td>54USD</td>
    </tr>
</table>
</body>
</html>
 
How exactly could i parse this so i can get the array ?

Code: Select all

 
$array = array(
    0 => array(
        0 => 'Boxer shorts',
        1 => '20USD'
    ),
    1 => array(
        0 => 'T-shirt',
        1 => '30USD'
    ),
    2 => array(
        0 => 'Pants',
        1 => '54USD'
    ),
);
 
I have like tried preg_replace with like

preg_replace();

But i allways fail. Anyone?

Re: Using preg_replace - HTML parse.

Posted: Thu Jun 05, 2008 5:18 am
by Benjamin
Your looking for a regular expression to use that would match all of the:
<tr>
<td>()</td>
<td>()</td>
</tr>
So it would be something like:

Code: Select all

 
preg_match_all('#<tr>\s{1,}<td>(.*?)</td>\s{1,}<td>(.*?)</td>\s{1,}</tr>#is', $html, $matches);
 
echo '<pre>', print_r($matches, true), '</pre>';