Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get last integer in a string?

Tags:

php

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?

like image 525
qadenza Avatar asked May 14 '26 20:05

qadenza


2 Answers

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:

  • preg_match_all()
  • end()

Tutorial for regex: tutorialspoint.com

Good tool to create regex: regexr.com

like image 161
paolobasso Avatar answered May 16 '26 10:05

paolobasso


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');
like image 44
Emissary Avatar answered May 16 '26 09:05

Emissary



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!