PHP如何从正文中删除某些属性

时间:2019-12-07 01:53:56

标签: php regex

我有以下变量$text,它触发了HTML负载。对于我来说,其中大多数对我没有用,但对我而言却不是。

出现的HTML:

<div class="feed-item-description">
<ul>
<li><strong>Impact:</strong>&nbsp;Low</li>
<li><strong>Severity:</strong> <span class="label label-info">Low</span></li>
</ul>
...

我想做什么

我想从本文中获得impactseverity的评分。我不需要标签。

我尝试这样做:

$itemAttributes = explode (':' , $text);

$impact     = $itemAttributes[3];
$severity   = $itemAttributes[4];

这确实确实给了我想要的属性,但后来也叫这个词。它的行为也很奇怪,即使我修剪它,也无法摆脱输出中的前一个空格。

它似乎也将其后的<div>封闭了,我无法解释。我敢肯定我会为使用Regex for HTML感到沮丧,但是我认为必须有一种方法可以使事情变得如此简单,因为每次在我想要的信息前都使用相同的词。

如果要在页面上查看实际输出,可以在这里查看:https://dev.joomlalondon.co.uk/,您可以在生成的输出中看到它关闭了<div class="feed-item-description">,但我不告诉它可以在任何地方执行此操作,而我使用的输出包含在<li>而不是<div>中。

2 个答案:

答案 0 :(得分:1)

也许

^\h*(Impact:)\s+(.*)|^\h+(Severity:)\s+(.*)

只需返回那些期望值。

测试

$re = '/^\h*(Impact:)\s+(.*)|^\h+(Severity:)\s+(.*)/m';
$str = 'Project: Joomla!
    SubProject: CMS
    Impact: Low
    Severity: Low
    Versions: 3.6.0 - 3.9.12
    Exploit type: Path Disclosure
    Reported Date: 2019-November-01
    Fixed Date: 2019-November-05
    CVE Number: CVE-2019-18674

Description

Missing access check in the phputf8 mapping files could lead to an path disclosure.
Affected Installs

Joomla! CMS versions 3.6.0 - 3.9.12';

preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);

var_dump($matches);

输出

array(2) {
  [0]=>
  array(3) {
    [0]=>
    string(15) "    Impact: Low"
    [1]=>
    string(7) "Impact:"
    [2]=>
    string(3) "Low"
  }
  [1]=>
  array(5) {
    [0]=>
    string(17) "    Severity: Low"
    [1]=>
    string(0) ""
    [2]=>
    string(0) ""
    [3]=>
    string(9) "Severity:"
    [4]=>
    string(3) "Low"
  }
}

如果您想简化/更新/探索表达式,请在regex101.com的右上角进行解释。如果您有兴趣,可以观看匹配的步骤或在this debugger link中进行修改。调试器演示了a RegEx engine如何逐步使用一些示例输入字符串并执行匹配过程的过程。


RegEx电路

jex.im可视化正则表达式:

enter image description here

答案 1 :(得分:0)

因为您确实应该使用DOMDocument来解析HTML,所以以下是使用它的解决方案:

$doc = new DOMDocument();
$doc->loadHTML($html);
$xpath = new DOMXPath($doc);
$feed_items = $xpath->query('//div[contains(@class, "feed-item-description")]');
foreach ($feed_items as $feed_item) {
    $impact_node = $xpath->query('//li[contains(string(), "Impact:")]', $feed_item);
    $impact = preg_replace('/Impact:\W*/', '', $impact_node->item(0)->textContent);
    echo $impact . "\n";
    $severity_node = $xpath->query('//li[contains(string(), "Severity:")]', $feed_item);
    $severity = preg_replace('/Severity:\W*/u', '', $severity_node->item(0)->textContent);
    echo $severity . "\n";
}

输出(用于示例HTML)

Low
Low

Demo on 3v4l.org