Ni Nho
Ni Nho

Reputation: 51

How to get content from a div using regex

I have string like :

<div class="fck_detail">
    <table align="center" border="0" cellpadding="3" cellspacing="0" class="tplCaption" width="1">
        <tbody>
            <tr><td>
            <img alt="nole-1375196668_500x0.jpg" src="http://l.f1.img.vnexpress.net/2013/07/30/nole-1375196668_500x0.jpg" width="500">                
            </td></tr>
            <tr><td class="Image">
                Djokovic hậm hực với các đàn anh. Ảnh: <em>Livetennisguide.</em>
            </td></tr>
        </tbody>
    </table>
    <p>Riêng với Andy Murray, ...</p>
    <p style="text-align:right;"><strong>Anh Hào</strong></p> 
</div>

I want to get content . How to write this pattern using preg_match. Please help me

Upvotes: 0

Views: 8398

Answers (1)

Brilliand
Brilliand

Reputation: 13714

If there are no other HTML tags inside the div, then this regex should work:

$v = '<div class="fck_detail">Some content here</div>';
$regex = '#<div class="fck_detail">([^<]*)</div>#';
preg_match($regex, $v, $matches);
echo $matches[1];

The actual regex here is <div class="fck_detail">([^<]*)</div>. Regexes used in PHP also need to be surrounded by some other character that doesn't occur in the regex (I used #).

However, if what you're parsing is arbitrary HTML provided by the user, then preg_match simply can't do this. Full-fledged HTML parsing is beyond the ability of any regex, and that's what you'll need if you're parsing the output of a full-fledged HTML editor.

Upvotes: 1

Related Questions