1

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

Mohammad
  • 21,175
  • 15
  • 55
  • 84
user186585
  • 512
  • 1
  • 8
  • 25
  • Possible duplicate of [How do you parse and process HTML/XML in PHP?](http://stackoverflow.com/questions/3577641/how-do-you-parse-and-process-html-xml-in-php) – chris85 Oct 26 '16 at 15:55

2 Answers2

2

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.
Jan
  • 42,290
  • 8
  • 54
  • 79
1

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.

Mohammad
  • 21,175
  • 15
  • 55
  • 84