qadenza
qadenza

Reputation: 9293

how to get last integer in a string?

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?

Upvotes: 3

Views: 1526

Answers (7)

Emissary
Emissary

Reputation: 10148

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');

Upvotes: 2

S. Imp
S. Imp

Reputation: 2895

I know this has been answered, but if you really want to get the last int in a line without referring specifically to attributes or tag names, consider using this.

$str = "
asfdl;kjas;lkjfasl;kfjas;lf  999 asdflkasjfdl;askjf
<span class='span1' data-id=2>lorem ipsum</span>
<span class='span2' data-id=14>lorem ipsum</span>


Look at me I end with a number 1234
";


$matches = NULL;
$num = preg_match_all('/(.*)(?<!\d)(\d+)[^0-9]*$/m', $str, $matches);

if (!$num) {
  echo "no matches found\n";
} else {
    var_dump($matches[2]);
}

It will return an array from a multiline input of the last integers for each line:

array(4) {
  [0] =>
  string(3) "999"
  [1] =>
  string(1) "2"
  [2] =>
  string(2) "14"
  [3] =>
  string(4) "1234"
}

Upvotes: 1

paolobasso
paolobasso

Reputation: 2018

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

Upvotes: 2

AurimasLazdauskas
AurimasLazdauskas

Reputation: 200

Wrote an appropiate function for this purpose.

function LastNumber($text){
    $strlength = strlen($text);   // get length of the string
    $lastNumber = '';             // this variable will accumulate digits
    $numberFound = 0;             

    for($i = $strlength - 1; $i > 0; $i--){   // for cicle reads your string from end to start
        if(ctype_digit($text[$i])){
            $lastNumber = $lastNumber . $text[$i];  // if digit is found, it is added to last number string;
            $numberFound = 1;  // and numberFound variable is set to 1
        }else if($numberFound){  // if atleast one digit was found (numberFound == 1) and we find non-digit, we know that last number of the string is over so we break from the cicle.
            break;
        }
    }
    return intval(strrev($lastNumber), 10); // strrev reverses last number string, because we read original string from end to start. Finally, intval function converts string to integer with base 10
}

Upvotes: 1

ΓDΛ
ΓDΛ

Reputation: 11100

 function find($path){

$countPath = strlen($path);

for ($i = 0; $i < $countPath; $i++) {

    if (substr($path, $i, 3) == "-id") {

        echo substr($path, $i + 4, 1);

    }
}}find($path1);

Upvotes: 1

aperpen
aperpen

Reputation: 728

I think that you should use regex, for example:

<?php
$paths = [];
$paths[] = '<span class=\'span1\' data-id=2>lorem ipsum dolor</span>';
$paths[] = '<span class=\'span2\' data-id=14>lorem ipsum</span>';
foreach($paths as $path){
    preg_match('/data-id=([0-9]+)/', $path, $data_id);
    echo 'data-id for '.$path.' is '.$data_id[1].'<br />';
}

This will output:

data-id for lorem ipsum dolor is 2

data-id for lorem ipsum is 14

Upvotes: 1

AmericanUmlaut
AmericanUmlaut

Reputation: 2837

Depending on how those variables get set, one solution could be to get the integer first and then inject it into the paths:

$dataId = 2;
$path1 = "<span class='span1' data-id='$dataId'>lorem ipsum</span>";

(Note that I added quotes around the data-id value, otherwise your HTML is invalid.)

If you aren't building the strings yourself, but need to parse them, I would not simply get the last integer. The reason is that you might get a tag like this:

<span class='span1' data-id='4'>Happy 25th birthday!</span>

In that case, the last integer in the string is 25, which isn't what you want. Instead, I would use a regular expression to capture the value of the data-id attribute:

$path1 = "<span class='span1' data-id='2'>lorem ipsum</span>";
preg_match('/data-id=\'(\d+)\'/', $path1, $matches);
$dataId = $matches[1];
echo($dataId); // => 2

Upvotes: 1

Related Questions