user186585
user186585

Reputation: 512

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

<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

Upvotes: 1

Views: 1932

Answers (2)

Jan
Jan

Reputation: 43169

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.

Upvotes: 3

Mohammad
Mohammad

Reputation: 21489

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.

Upvotes: 1

Related Questions