-1

我只是想做的是采用以下代码:

$Anchors = '<a href="#" class="test1"><div class="test2"><a href="#" class="test3"><div class="test4">'

并获取最后一个锚标记的类属性值,在本例中为“test3”。到目前为止,我有这个:

if(preg_match('/(<a\s.*)(class="|\')([^-\'"]*)("|\')?.*?([^>])/i',$Anchors,$matches)){

但显然它没有做我想做的事,有什么帮助吗?

4

2 回答 2

2

描述

这个正则表达式将:

  • 匹配字符串中的最后一个锚标记
  • 捕获类属性的值
  • 避免在搜索 html 字符串时使用正则表达式的许多潜在问题

 

.*<a\b(?=\s) # capture the open tag
(?=(?:[^>=]|='[^']*'|="[^"]*"|=[^'"][^\s>]*)*?\sclass=['"]([^"]*)['"]?)  # capture the src attribute value
(?:[^>=]|='[^']*'|="[^"]*"|=[^'"\s]*)*"\s?\/?> # get the entire  tag

在此处输入图像描述

例子

现场示例:http ://www.rubular.com/r/G5F6AD5UyL

示例文本

请注意,最后一个标签有一个困难的边缘情况

<a href="#" class="test1"><div class="test2">
<a onmouseover=' class="NotTheClass" ; funClassRotator(class) ; ' class="test3" href="#" ><div class="test4">

捕获组

[0][0] = <a href="#" class="test1"><div class="test2"><a href="#" onmouseover=' class="NotTheClass" ; funClassRotator(class) ; ' class="test3">
[0][1] = test3
于 2013-07-12T19:16:22.480 回答
1

使用ganonsimplehtmldom会更快

例如使用 simplehtmldom

foreach($html->find('a') as $element)
   echo $element->class . '<br>';
于 2013-07-12T17:20:10.403 回答