我想解析一个HTML文档并获取所有用户的昵称。
格式如下:
<a href="/nickname_u_2412477356587950963">Nickname</a>
如何在PHP中使用正则表达式?我不能使用DOMElement或简单的HTML解析
下面是不使用正则表达式的工作解决方案:
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);
}
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解析器上使用Regex的免责声明适用。以上可能可以改进为更可靠的匹配。