首先,这就是你
应该
提出了以下问题:
在以下示例HTML数据中:
<a href="profile/xalil">
<li>
<img src="../users/avatar/small/thumb_default.jpg" />
<p>xalil eshghi</p>
<span></span>
</li>
</a>
href
img src
这个
p
内容和
span
我尝试使用以下regexp。。。。。。。。。
the wrong approach
你
能够
<s([^>]+)([^<]+)<\/span>
使用:
<span>([^<]*)<\/span>
……然而,这不仅仍然很难理解,而且还不能解释所有可能的边缘情况。
img
标记在
src
? 由于使用了
[\s\S]+
在模式中-这可能会导致正则表达式跳转到HTML的一个完全不同的部分!
这个问题可以而且应该通过使用DOM解析器轻松解决。
<?php
// This is just some boilerplate code for the sake of completion...
$doc = new DOMDocument();
$doc->loadHTMLFile("your_page.html");
$xpath = new DOMXpath($doc);
// Do you want to scope your results to within <ul class="users"> ?
// If not, just use: $links = $xpath->query("//a");
$links = $xpath->query("//ul[@class='users']/a");
// Guard clause
if (is_null($links)) { return; }
$result = array();
foreach ($links as $link) {
$href = $link->getAttribute('href'); // PART 1 - Get the href
$img = $xpath->query("li/img", $link)[0];
$img_src = $img->getAttribute('src'); // PART 2 - Get the img src
$p = $xpath->query("li/p", $link)[0];
$p_text = $p->textContent; // PART 3 - Get the p contents
$span = $xpath->query("li/span", $link)[0];
$span_text = $span->textContent; // PART 4 - get the span contents
$result[] = [$href, $img_src, $p_text, $span_text];
}
print_r($result);
?>