2011-08-14 57 views
0

我想解析一个HTML文档并获取所有用户的昵称。HTML分析正则表达式

他们都是这种格式:

<a href="/nickname_u_2412477356587950963">Nickname</a> 

我能如何使用PHP中的regular expression呢?我无法使用DOMElement或简单的HTML解析。

+5

Oblig:http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454 – Oded

+6

出于纯粹的好奇心,为什么你不能使用HTML解析器? –

+0

你不需要一个正则表达式,你可以用[DomDocument :: loadHTML()](http://www.php.net/manual/en/domdocument.loadhtml.php)来完成。 – arnaud576875

回答

3

这里是不使用正则表达式的工作液:

的DomDocument :: loadHTML()是忘记足以对畸形HTML工作。

<?php 
    $doc = new DomDocument; 
    $doc->loadHTML('<a href="/nickname_u_2412477356587950963">Nickname</a>'); 

    $xpath = new DomXPath($doc); 
    $nodes = $xpath->query('//a[starts-with(@href, "/nickname")]'); 

    foreach($nodes as $node) { 
     $username = $node->textContent; 
     $href = $node->getAttribute('href'); 
     printf("%s => %s\n", $username, $href); 
    } 
+0

谢谢,但你们不明白我的意思,“昵称”是一个变量,所以这个随机数字集 –

3
preg_match_all(
    '{     # match when 
     nickname_u_  # there is nickname_u 
     [\d+]*   # followed by any number of digits 
     ">    # followed by quote and closing bracket 
     (.*)?   # capture anything that follows 
     </a>   # until the first </a> sequence 
    }xm', 
    '<a href="/nickname_u_2412477356587950963">Nickname</a>', 
    $matches 
); 
print_r($matches); 

了一个多HTML parser对HTML使用正则表达式平时免责声明适用。以上可能可以改进到更可靠的匹配。 It will work for the example you gave though.