【问题标题】:remove span tag with a certain color style php删除具有某种颜色样式php的span标签
【发布时间】:2013-09-27 08:18:54
【问题描述】:

我正在从网页读取数据,但我需要帮助编写 preg_replace 函数的模式。

网页在样式 color=#767676 的 span 标签内包含“没有能力、影响或权力”

我希望能够只输出没有跨度标签的“没有能力、影响或权力”。有什么办法可以根据 span 标签内的样式颜色来做到这一点?因为文件中还有很多其他的span标签。

这是我写的代码:

$link="http://www.myWebsite.com";
$inputlink = @file_get_contents($link) or die('Could not access file: $link');
    // To output the span tag that has style=color:#767676
$outputlink = preg_replace('/(<[^>]+) style="color:#767676"/i', '$1', $inputlink);
    // To remove the span tags
$string = preg_replace("/<span[^>]+\>/i", "", $outputlink);
echo strip_tags($string);//OUTPUT : Without ability, influence, or power

我将整个网站内容作为输出。如果你能给我一个链接,我可以学习写作模式,我也非常感激。

谢谢

【问题讨论】:

  • 你的意思是页面数据是&lt;span style=color:#767676&gt;Without ability, influence, or power&lt;/span&gt;NOTHING吗?
  • 不,这是一个带有许多其他 span 和 div 标签的网页。但是我想不出任何其他方法来提取这个特定的文本:“没有能力、影响或权力”,所以我在想是否有办法根据它的颜色来提取它。
  • 你使用了strip_tags(),它删除了span和其他标签,那么使用preg_replace()的原因是什么?!
  • 我使用第一个 preg_replace 仅获取 color style=#767676 的 span 标签并删除所有其他标签(其他 span 标签和标签之间有内容的 div 标签)。我只想检索这个字符串:“没有能力、影响力或权力”。我使用第二个 preg_replace 删除 span 标签,但我的方法可能是错误的。还有其他解决方法吗?任何建议将不胜感激。

标签: php regex preg-replace


【解决方案1】:

你可以用这个:

<?php

$link = 'http://www.myWebsite.com';
$inputlink = @file_get_contents($link) or die('Could not access file: $link');

我假设页面“http://www.myWebsite.com”是这样的:

<span style="color:#767676">Without ability, influence, or power</span> <span>if you see this part or see last part in gray color, your regexp is wrong!</span>

现在让我们写一些正则表达式

$pattern = '/<span style="color:#767676">([^<]+)(?<!<\/span>)<\/span>/';
preg_match($pattern, $text, $matches);
echo $matches[1];

它将输出Without ability, influence, or power,不带&lt;span&gt;标签。

【讨论】:

  • 我将模式更改为更短的形式。现在您也可以从模式中删除 (?&lt;!&lt;\/span&gt;) 以缩短。
猜你喜欢
  • 2019-02-19
  • 2021-10-15
  • 2012-04-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-18
相关资源
最近更新 更多