取 PHP 中是否有整数部分作为字符串变量的尾部


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

如何在PHP中将字符串变量的整数部分(最后一个整数)提取到另一个整数变量中。

这是我的代码的当前状态:

<?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
 ...
?>

我所需要的只是当整数是$part中的最后一件事时,才将整数部分从$path'node/'出来。

如果$path是:

  • "绿页/12432/节点",或
  • "56372/页/2321",或
  • "节点/56372/页"。

我不想经历冗长的代码,例如:

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

我必须在很多地方使用这个 43562。希望它可以通过任何简单的preg_方法或复杂的正则表达式来实现。

等待最小 LOC 解决方案。

您可以通过多种方式获得该数字。

这是一个简单的正则表达式:

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

如果检查前缀是否也存在很重要,则:

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

您还可以使用 strrpos()substr()

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

也可以只砍掉绳子。它有点快,但它有效:

$parts = explode('/', $path);
echo array_pop($parts);
$string = "foo/bar/node/1234";
if(preg_match('/node'/([0-9]+)$/', $string, $match)) {
        echo $match[1];
}