从字符串中提取Span和href数据

时间:2014-01-24 11:18:02

标签: php regex

我有一些这种格式的HTML字符串

   <span>SpanText</span>
   <a href="link.html" title="link">Link Text</a>

我使用此正则表达式来提取数据

   $regexp = "<span>(.*)<\/span><a\s[^>]*href=(\"??)([^\" >]*?)\\1[^>]*>(.*)<\/a>";
   preg_match_all("/$regexp/siU", $string, $matches, PREG_SET_ORDER);

这不会返回任何内容。

正则表达式一定有问题吗?

我想提取范围文本和链接文本。

2 个答案:

答案 0 :(得分:1)

您可以使用正则表达式:

<span>(.*)<\/span>(?:.|\n)*?<a\s[^>]*?href=\"??[^\" >]*?[^>]*>(.*)<\/a>

DEMO

您的代码出现问题:

为什么使用\\1? (我不明白)

答案 1 :(得分:0)

不要使用正则表达式来解析DOM,它不是适合它的工具......而是使用DOM解析器......以下是 PHP简单HTML DOM解析器的示例:

// includes Simple HTML DOM Parser
include "simple_html_dom.php";

$input = '
            <span>SpanText</span>
            <a href="link.html" title="link">Link Text</a>
        ';

//Create a DOM object
$html = new simple_html_dom();
// Load HTML from a string
$html->load($input);

// Retrieve the text from elements
$span = $html->find('span',0)->plaintext;
$anchor = $html->find('a',0)->plaintext;

echo "$span - $anchor";

// Clear DOM object
$html->clear();
unset($html);

<强>输出

SpanText - Link Text

Working DEMO

有关详细信息,请参阅PHP Simple HTML DOM Parser Manual

了解详情

但是,如果你只是在这段html代码上工作,那么可以在这里使用正则表达式... 所以你可以尝试这种模式:

/<span>([^<]+)<\/[^<]+<a[^>]+>([^<]+)/g

Live DEMO

相关问题