从 html 文档中限定的 span 标记中获取类值和文本

Get class value and text from qualifying span tags in html document

提问人:Sepp Hofer 提问时间:8/11/2021 最后编辑:mickmackusaSepp Hofer 更新时间:8/11/2021 访问量:508

问:

请帮助我使用以下模式进行preg_match_all

如何更改我的模式以获得所需的输出?

在字符串中,搜索类名类似于 '' ( OR OR OR 的标签email_email_email_p_12email_22email_xx)

获取标签之间的文本<span class=" xx email_xx xx "> THE EMAIL ADDRESS </span>

获取以“email_”开头的类名

这是我的模式:$pattern = '~<span class=\"((.*?)*)*(email_(.*?))?(.*?)\">(.*?)</span>~';

我需要的是这样的数组:

Array
(
    [0] => Array
        (
            [mail] => [email protected]
            [class] => email_p_14
        )

    [1] => Array
        (
            [mail] => [email protected]
            [class] => email_p_22
        )

    [2] => Array
        (
            [mail] => [email protected]
            [class] => email_ 
        )

    [3] => Array
        (
            [mail] => [email protected]
            [class] => email_
        )

)

文件:

<?php
    
$string = '
<p>
Lorem ipsum dolor sit amet, 
consectetur adipisicing elit, 
sed do eiusmod tempor incididunt ut

    <span class=" red email_p_14">[email protected]</span>

dolore magna aliqua. Ut enim ad minim veniam, 
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea consequat. 
Duis aute irure in reprehenderit in voluptate velit

    <span class="email_p_22">[email protected]</span>

dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, 
sunt in culpa qui officia deserunt mollit

    <span class="blue email_ green">[email protected]</span>

laborum. Donec elementum ligula.
Quis nostrud exercitation ullamco 

    <span class="blue email_ green black">[email protected]</span>

aliquip ex ea consequat. 
</p>';


/* Looking for these:

<span class=" red email_p_14">[email protected]</span>
<span class="email_p_22">[email protected]</span>
<span class="blue email_ green">[email protected]</span>
<span class="blue email_ green black">[email protected]</span>

*/


$pattern = '~<span class=\"((.*?)*)*(email_(.*?))?(.*?)\">(.*?)</span>~';

preg_match_all($pattern, $string, $m);

$clean_array = array_filter(array_map('array_filter', $m));

ksort($clean_array);
$output = Array();

foreach($clean_array as $row) {
    foreach($row as $key => $val){
        $output[$key][]=$val;
    }
}
print("<pre>".print_r($output,true)."</pre>");

这是我得到的:

Array
(
    [0] => Array
        (
            [0] => [email protected]
            [1] =>  red email_p_14
            [2] => [email protected]
        )

    [1] => Array
        (
            [0] => [email protected]
            [1] => email_
            [2] => p_22
            [3] => [email protected]
        )

    [2] => Array
        (
            [0] => [email protected]
            [1] => blue email_ green
            [2] => [email protected]
        )

    [3] => Array
        (
            [0] => [email protected]
            [1] => blue email_ green black
            [2] => [email protected]
        )

)
    

我需要的是这样的数组:

Array
(
    [0] => Array
        (
            [mail] => [email protected]
            [class] => email_p_14
        )

    [1] => Array
        (
            [mail] => [email protected]
            [class] => email_p_22
        )

    [2] => Array
        (
            [mail] => [email protected]
            [class] => email_ 
        )

    [3] => Array
        (
            [mail] => l[email protected]
            [class] => email_
        )

)
*/
php 数组 dom xpath html 解析

评论

0赞 mickmackusa 8/11/2021
我们不使用正则表达式解析 html。
0赞 mickmackusa 8/12/2021
你知道你有点赞特权,对吧?如果您发现任何正确的答案对您有帮助,您可以通过为每个答案投赞成票来感谢他们。这也向未来的研究人员发出信号,表明您推荐答案中的建议。我不需要更多的积分,thefourthbird也不需要更多的积分,但你应该了解你拥有的工具。

答:

1赞 The fourth bird 8/11/2021 #1

对于类值,您可以使用此模式,该模式使用重复捕获组的组合,其中 all 实际上是可选的。((.*?)*)*(email_(.*?))?(.*?)

对于您使用的电子邮件地址,它与任何字符 non greedy 匹配并且与类似电子邮件的模式不匹配。(.*?)

您可以使用命名捕获组来获取密钥,并且:mailclass

<span[^<>]*\bclass="[^"]*(?<class>email_[^\s"]*)[^"]*">\h*(?<mail>[^\s@]+@[^\s@]+)\h*<\/span>

正则表达式演示 |PHP 演示

在结果中,删除数字键:

$re = '`<span[^<>]*\bclass="[^"]*(?<class>email_[^\s"]*)[^"]*">\h*(?<mail>[^\s@]+@[^\s@]+)\h*<\/span>`';
$str = '<span class=" xx email_p_14 xx "> [email protected] </span>';

preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);
print_r(array_filter($matches[0], function ($k) { return !is_numeric($k); }, ARRAY_FILTER_USE_KEY));

输出

Array
(
    [class] => email_p_14
    [mail] => [email protected]
)

您还可以做的是查看 DOMDocument,找到类名以 email_ 开头的跨度,然后匹配电子邮件地址的跨度值,例如模式。

然后,您可以使用键和值构建数组。

例如

$str = '<span class=" xx email_p_14 xx "> [email protected] </span>';
$dom = new DomDocument();
$dom->loadHTML($str, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
$doc = new DOMXPath($dom);

$items = $doc->query("//span[contains(@class, 'email_')]");

foreach ($items as $item) {
    $class = array_filter(explode(' ', $item->getAttribute('class')), function($x) {
        return substr( $x, 0, 6 ) === "email_";
    });
    print_r($class);
    echo $item->nodeValue;
}

输出

Array
(
    [2] => email_p_14
)
 [email protected] 

PHP 演示

2赞 mickmackusa 8/11/2021 #2

使用 DOMDocument 和 XPath 解析 html。定位到适当的节点后,挖掘并提取数据,然后将新的子数组推送到结果中。

代码:(演示)

$dom = new DOMDocument;
libxml_use_internal_errors(true);
$dom->loadHTML($string);
$xpath = new DOMXPath($dom);

$result = [];
foreach ($xpath->query("//span[starts-with(@class, 'email_') or contains(@class, ' email_')]") as $span) {
    $result[] = [
         'mail' => $span->nodeValue,
         'class' => preg_replace(
             '~.*\b(email_\S*).*~',
             '$1',
             $span->getAttribute('class')
         )
    ];
}
var_export($result);

输出:

array (
  0 => 
  array (
    'mail' => '[email protected]',
    'class' => 'email_p_14',
  ),
  1 => 
  array (
    'mail' => '[email protected]',
    'class' => 'email_p_22',
  ),
  2 => 
  array (
    'mail' => '[email protected]',
    'class' => 'email_',
  ),
  3 => 
  array (
    'mail' => '[email protected]',
    'class' => 'email_',
  ),
)

评论

1赞 Sepp Hofer 8/11/2021
多谢!这是按要求工作的。我认为这个答案最能涵盖这个问题。也非常紧凑,清晰和优雅。
0赞 The fourth bird 8/12/2021
不错的解决方案,值得更多赞誉。++