1

First of all I am new to PHP.

Normally I can do preg_match tag for a <div class="T-time">(.*)</div> and read the content but I could not do the same thing for:

<div class="T-date"> <a href=" different link ">123</a> </div>

Is it possible to preg_match tag for the 123 result when the link is different every time in the <a href=> tag ?

Thanks from now.

Andy Lester
  • 91,102
  • 13
  • 100
  • 152
Luai Kalkatawi
  • 1,492
  • 5
  • 25
  • 51
  • I think you mean [`preg_match`](http://php.net/manual/en/function.preg-match.php) – brbcoding Apr 17 '13 at 15:25
  • Fixed sorry Thank @brbcoding – Luai Kalkatawi Apr 17 '13 at 15:26
  • Just as a warning: http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags – Bart Friederichs Apr 17 '13 at 15:27
  • Thanks @BartFriederichs but isn't different from my question? – Luai Kalkatawi Apr 17 '13 at 15:31
  • @LuaiKalkatawi I think he's making the point that you shouldn't really be parsing HTML with regex, the structure of the langauge does not work well with it. The question you should be asking is do you need to use regex? There are HTML parsers or something like jQuery if doing it client side that makes it much easier. – MatthewMcGovern Apr 17 '13 at 15:34
  • @MatthewMcGovern so I need to use HTML parsers or jQuery to solve this issue? I really don't know much about web service. I just want to pull that data to iPhone. I am just writing the php so I can parse the data from there. – Luai Kalkatawi Apr 17 '13 at 15:38
  • @LuaiKalkatawi I didn't mean you have too, it would entirely depend on what you need it for. As in, why are you using regex on some HTML anyway? – MatthewMcGovern Apr 17 '13 at 15:40
  • **Don't use regular expressions to parse HTML**. You cannot reliably parse HTML with regular expressions, and you will face sorrow and frustration down the road. As soon as the HTML changes from your expectations, your code will be broken. See http://htmlparsing.com/php for examples of how to properly parse HTML with PHP modules that have already been written, tested and debugged. – Andy Lester Apr 17 '13 at 15:50

1 Answers1

3

It's better to do it using DOM parser like this:

$input = 'html input';
$html = new DOMDocument();
$html->loadHTML($input);

foreach($html->getElementsByTagName('div') as $div)
{
    if($div->getAttribute('class') == 'T-date')
    {
        foreach($div->getElementsByTagName('a') as $link)
            echo ($link->getAttribute('href') . "\t" . $link->nodeValue . "\n");
    }
}

but if you still want to use preg_match you can use this:

$str = '<div class="T-date"> <a href=" different link ">123</a> </div>';
preg_match('/<div class="T-time"><a.*?>(.*?)<\/a></div>/', $str, $matches);
print_r($matches);
razz
  • 9,770
  • 7
  • 50
  • 68