【问题标题】:I want to extract only the contents enclosed in tags using regular expressions我只想使用正则表达式提取标签中包含的内容
【发布时间】:2022-02-05 17:29:08
【问题描述】:

我有一个插入了 标记的文本。我想使用 PHP 仅从该文本中提取 span 中包含的内容。我无法获得预期的结果。我想知道我应该使用什么样的正则表达式来获得预期的结果。

[我想做的事]

我只想提取egg标签的内容。

[搜索目标字符串]

我吃了一个煮鸡蛋火腿

我吃了一个火腿和鸡蛋

[正则表达式]

(?<="|egg|">).+?(?=</span)

[预期结果]

  • 煮鸡蛋
  • 火腿和鸡蛋

[实际结果]

  • egg">煮鸡蛋和火腿
  • egg ham">火腿和鸡蛋

【问题讨论】:

  • 尝试使用 DOMDocument,这样可以理解文本 (HTML) 的结构,并且可以更可靠地工作。

标签: php html nsregularexpression


【解决方案1】:

这可能是你想要的:

<span class=".*?egg.*?">(.+?)<\/span>

使用 PHP,你可以通过以下方式获取你想要的数据:

preg_match_all('/<span class=".*?egg.*?">(.+?)<\/span>/',$text_you_got,$matches);

测试代码:

$text_you_got = 'I ate a <span class="egg">boiled egg</span> and <span class="ham">ham</span>.I ate a <span class="egg ham">ham and eggs</span>.';
preg_match_all('/<span class=".*?egg.*?">(.+?)<\/span>/',$text_you_got,$matches);
var_dump($matches);

结果:

array(2) {
  [0]=>
  array(2) {
    [0]=>
    string(35) "<span class="egg">boiled egg</span>"
    [1]=>
    string(78) "<span class="ham">ham</span>.I ate a <span class="egg ham">ham and eggs</span>"
  }
  [1]=>
  array(2) {
    [0]=>
    string(10) "boiled egg"
    [1]=>
    string(12) "ham and eggs"
  }

}

如图所示,你可以通过以下方式简单地得到你想要的结果:

$text_you_got = 'I ate a <span class="egg">boiled egg</span> and <span class="ham">ham</span>.I ate a <span class="egg ham">ham and eggs</span>.';
preg_match_all('/<span class=".*?egg.*?">(.+?)<\/span>/',$text_you_got,$matches);
foreach($matches[1] as $item)
{
    echo $item."\n";
}

【讨论】:

  • 感谢您的评论。然而,结果并不如预期。以下是搜索结果。 &lt;span class="egg"&gt;boiled egg&lt;/span&gt;&lt;span class="egg ham"&gt;ham and eggs&lt;/span&gt;
  • 是的,它匹配整个模式,但你需要的是获取这个 RegEx 的捕获组。
  • 你想要的答案其实在数组$matches中。 $matches 包含目标捕获组的项目
  • 这可以为您提供有关捕获组的更多信息:phptutorial.net/php-tutorial/regex-capturing-groups
  • 我已经更新了答案,如果你现在能得到你想要的答案,请查看:)
猜你喜欢
  • 1970-01-01
  • 2010-10-09
  • 1970-01-01
  • 2015-12-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-30
  • 1970-01-01
相关资源
最近更新 更多