dongxia19772008 2015-01-02 04:52
浏览 43
已采纳

如果在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.

  • 写回答

2条回答 默认 最新

  • douzi7890 2015-01-02 04:58
    关注

    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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化