2013-04-17 129 views
1

首先我是PHP新手。php preg_match <a href>

通常情况下,我可以为<div class="T-time">(.*)</div>preg_match标签和阅读内容,但我不能为做同样的事情:

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

是否有可能preg_match标记为123结果当链路<a href=>标签中每次都不同?

从现在开始感谢。

+0

我想你的意思['preg_match'] (http://php.net/manual/en/function.preg-match.php) – brbcoding

+0

修正了很抱歉谢谢@brbcoding –

+0

就像一个警告:http://stackoverflow.com/questions/1732348/regex-match-open -tags-except-xhtml-self-contained-tags –

回答

3

这是更好地使用DOM解析器这样做:

$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"); 
    } 
} 

,但如果你仍然想使用preg_match您可以使用此:

$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);