duanmou9228 2013-08-29 15:58
浏览 193
已采纳

如何在php中提取字符串末尾的值

In my php code I have an array of variables starting with a word followed by an (random) number:

x[0] = 'justaword8'
x[1] = 'justaword5'
x[2] = 'justaword4'
etc.

I know i must use a foreach loop, but how to extract the figures at the end of each word? (I assume I could use preg_match() but have no idea how specify that function exactly?)

  • 写回答

5条回答 默认 最新

  • dongxiaoxiao1983 2013-08-29 16:00
    关注

    Since the number varies in length, between one or two digits, you can use preg_match() like this:

    foreach( $array as $x) {
        preg_match( '/(\d{1,2})$/', $x, $match);
        echo "The number is: " . $match[1];
    }
    

    However, since the prefix is known ahead of time, just remove it directly (as per Marc B's comment, with an example usage):

    $prefix = "justaword";
    $length = strlen( $prefix);
    
    foreach( $array as $x) {
        echo "The number is: " . substr( $x, $length);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?