0

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.

1

2 Answers 2

1

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);
Sign up to request clarification or add additional context in comments.

Comments

1
$string = "foo/bar/node/1234";

if(preg_match('/node\/([0-9]+)$/', $string, $match)) {

        echo $match[1];
}

1 Comment

You mean $match[1], don't you?

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.