How To Get Specific Attribute Of Html In String Using Php?
I got a string and I need to find out all the data-id numbers. This is the string bla bla...
Which gives you
Solution 1:
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.Solution 2:
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]) // return2,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.
Post a Comment for "How To Get Specific Attribute Of Html In String Using Php?"