I have variables like this:
$path1 = "<span class='span1' data-id=2>lorem ipsum</span>";
$path2 = "<span class='span2' data-id=14>lorem ipsum</span>";
I need to get value of data-id but I think it's not possible in php.
Maybe is possible to get last integer in a string ? Something like:
$a = $path1.lastinteger(); // 2
$b = $path2.lastinteger(); // 14
Any help?
You could use a simple regex:
/data-id=[\"\']([1-9]+)[\"\']/g
Then you can build this function:
function lastinteger($item) {
preg_match_all('/data-id=[\"\']([1-9]+)[\"\']/',$item,$array);
$out = end($array);
return $out[0];
}
Working DEMO.
The full code:
function lastinteger($item) {
preg_match_all('/data-id=[\"\']([1-9]+)[\"\']/',$item,$array);
$out = end($array);
return $out[0];
}
$path1 = "<span class='span1' data-id=2>lorem ipsum</span>";
$path2 = "<span class='span2' data-id=14>lorem ipsum</span>";
$a = lastinteger($path1); //2
$b = lastinteger($path2); //14
References:
Tutorial for regex: tutorialspoint.com
Good tool to create regex: regexr.com
If you'd rather not use a regular expression you can use the DOM API:
$dom = DOMDocument::loadHTML($path2);
echo $dom->getElementsByTagName('span')[0]->getAttribute('data-id');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With