简体   繁体   English

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

[英]Extracting Span and href data from a string

I have some HTML strings with this format 我有一些具有这种格式的HTML字符串

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

I use this regexp to extract the data 我使用此正则表达式提取数据

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

This returns nothing. 这什么也不会返回。

There must be a problem with the regexp ? regexp一定有问题吗?

I want to extract the span text and the link text. 我要提取跨度文本和链接文本。

You can use the regex : 您可以使用regex:

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

DEMO DEMO

Problem with your code: 您的代码有问题:

Why you used \\\\1 ? 为什么使用\\\\1 (I didnt understand that) (我不明白)

Do not use regex to parse DOM, it's not the appropriate tool for that... Instead use a DOM parser... Here's an example with PHP Simple HTML DOM Parser : 不要使用正则表达式来解析DOM,这不是用于DOM的合适工具...而是使用DOM解析器...这是PHP Simple HTML DOM Parser的示例:

// 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);

OUTPUT OUTPUT

SpanText - Link Text

Working DEMO 工作演示

For more information, you can read more on PHP Simple HTML DOM Parser Manual 有关更多信息,您可以在PHP Simple HTML DOM Parser Manual上阅读更多内容。

But, if you're working only on this piece of html code, then maybe regex can be used here... So you can try this pattern: 但是,如果您仅在处理这段html代码,则可以在这里使用正则表达式...因此,您可以尝试以下模式:

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

Live DEMO 现场演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM