Search code examples
phpstringintegerstring-conversion

Take if there is an integer part as the tail of a string variable in PHP


How to extract the integer part(the last integer) of a string variable to another integer variable in PHP.

Here is the current status of my code:

<?php
 $path = current_path(); // eg. loading 'node/43562' to $path
 $pos = strpos($path, 'node/');
 if($pos>-1)die(print $pos); // sometimes $pos can be 0, may be 5 or even 26..like so
 ...
?>

All I need is to get the integer part comes after 'node/' out from $path only if the integer is the last thing in the $part.

Do nothing if $path is:

  • 'greenpage/12432/node', or
  • '56372/page/2321', or
  • 'node/56372/page'.

I don't want to go through lengthy codes like:

<?php
 $arr = explode(":",$path);
 $a= $arr[1];
 $b= $arr[3];
 $c= $arr[5];
 ...
 ...
?>

I have to use this 43562 in many places. Hope it can be implemented with any simple preg_ methods, or a complex regex.

Waiting for the minimal LOC solution.


Solution

  • You can get to the number in a myriad of ways.

    Here is a simple regex:

    preg_match('/\d+$/', $path, $match);
    var_dump($match);
    

    If it is important to check that the prefix is also there then:

    preg_match('/(?<=node\/)\d+$/', $path, $match);
    var_dump($match);
    

    You can also use strrpos() and substr():

    $slash = strrpos($path, '/');
    if ($slash !== false) {
        echo substr($path, $slash + 1);
    }
    

    It is also possible to just chop up the string. It is a little quick'n'dirty, but it works:

    $parts = explode('/', $path);
    echo array_pop($parts);