如何使用PHP获取字符串中的html的特定属性?

问题描述:

I got a string and I need to find out all the data-id numbers. This is the string

<li data-type="mentionable" data-id="2">bla bla... 
<li data-type="mentionable" data-id="812">some test 
<li>bla bla </li>more text 
<li data-type="mentionable" data-id="282">

So in the end It will find me this : 2,812,282

我有一个字符串,我需要找出所有 data-id code>数字。 这是字符串 p>

 &lt; li data-type =“availableable”data-id =“2”&gt; bla bla ... 
&lt; li data-type  =“提及”data-id =“812”&gt;某些测试
&lt; li&gt; bla bla&lt; / li&gt;更多文字
&lt; li data-type =“提及”data-id =“282”&gt; \  n  code>  pre> 
 
 

所以最后它会找到我: 2,812,282 code> p> div>

You can use regex to find target part of string in preg_match_all().

preg_match_all("/data-id=\"(\d+)\"/", $str, $matches);
// $matches[1] is array contain target values
echo implode(',', $matches[1]) // return 2,812,282

See result of code in demo

Because your string is HTML, you can use DOMDocument class to parse HTML and find target attribute in document.

Use DOMDocument instead:

<?php

$data = <<<DATA
<li data-type="mentionable" data-id="2">bla bla... 
<li data-type="mentionable" data-id="812">some test 
<li>bla bla </li>more text 
<li data-type="mentionable" data-id="282">
DATA;

$doc = new DOMDocument();
$doc->loadHTML($data, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);

$xpath = new DOMXPath($doc);

$ids = [];
foreach ($xpath->query("//li[@data-id]") as $item) {
    $ids[] = $item->getAttribute('data-id');
}
print_r($ids);
?>


Which gives you 2, 812, 282, see a demo on ideone.com.