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

1

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

2 Comments

Implode would give desired output, echo implode(',', $matches[1]);.
@chris85 Good mention

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.