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 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)