tags:

views:

49

answers:

4

I have he following scenario:

Got an HTML template file that will be used for mailing. Here is a reduced example:

    <table>
<tr>
<td>Heading 1</td>
<td>heading 2</td>
</tr>
<PRODUCT_LIST>
<tr>
<td>Value 1</td>
<td>Value 2</td>
</tr>
</PRODUCT_LIST>
</table>

All I need to do is to get the HTML code inside <PRODUCT_LIST> and then repeat that code as many times as products I have on an array.

What would be the right PHP Regex code for getting/replacing this List?

Thanks!

+3  A: 

Use Simple HTML DOM Parser. It's easy to understand and use .

$html = str_get_html($content);
$el = $html->find('PRODUCT_LIST', 0);
$innertext = $el->innertext;
webbiedave
A: 

Use this function. It will return all found values as an array.

<?php
function get_all_string_between($string, $start, $end)
{
    $result = array();
    $string = " ".$string;
    $offset = 0;
    while(true)
    {
        $ini = strpos($string,$start,$offset);
        if ($ini == 0)
            break;
        $ini += strlen($start);
        $len = strpos($string,$end,$ini) - $ini;
        $result[] = substr($string,$ini,$len);
        $offset = $ini+$len;
    }
    return $result;
}

$result = get_all_string_between($input_string, '<PRODUCT_LIST>', '</PRODUCT_LIST>');
shamittomar
HTML is not regular. Something like this will work for the simple example provided, but it won't work for something with nested tags (`<foo><PRODUCT_LIST><bar><PRODUCT_LIST><baz /></PRODUCT_LIST></bar><buz/></PRODUCT_LIST></foo>`). So it's not a good generic solution (no -1 since it does fit the needs of the example provided)... The better and more generic solution would be to use a DOM parser (SimpleXML, DomDocument, SimpleHtmlDom, etc)...
ircmaxell
@ircmaxell, yes I agree. But as he is specifying his **own** tags, it may be regular. Just another way to solve it.
shamittomar
@shamittomar: I'm not saying it can't be done or it's "bad" to do (otherwise I would have `-1`)... I'm just saying it's not a generic solution. It's perfectly OK as long as the problem scope fits within the limitations of the solution. I was just pointing out the limitations (so that the problem scope can be better assessed)...
ircmaxell
@ircmaxell, Yes I agree fully with you.
shamittomar
A: 

Assuming <PRODUCT_LIST> tags will never be nested

preg_match_all('/<PRODUCT_LIST>(.*?)<\/PRODUCT_LIST>/s', $html, $matches);

//HTML array in $matches[1]
print_r($matches[1]);
MooGoo
<PRODUCT_LIST> tags will never be nested, but using this code i get two empty matches...array(2) { [0]=> array(0) {} [1]=> array(0) {}}
Bathan
Using the HTML snippet you pasted, I get an array with only one element containing the HTML inside the PRODUCT_LIST tags. Perhaps you should post a more complete HTML sample.
MooGoo
Thanks dude! I had a typo on the HTML.This works just fine
Bathan
A: 

try this

<PRODUCT_LIST>(.*?)<\/PRODUCT_LIST>