du7133 2014-05-18 10:47
浏览 50
已采纳

php正则表达式检测索引级别

I had a look at regular expressions in PHP but I don't really understand how they work.

I have various strings like "1-title" , "1-1-secondTitle", "1-2-otherTitle", This goes up to three level ("1-2-1-text"), so on every string I have this formating and I would like to check if there is one, two or three number before the string starts and then output "0", "1" or "2".

So to make it clearer

"1-index" should return "0"

"3-1-text" should return "1"

"5-2-1-otherTitle" should return "2"

is it possible to check the number of char before the first letter on a string?

  • 写回答

1条回答 默认 最新

  • dougang6178 2014-05-18 11:03
    关注

    Alternaatively, if you dont want to use regex, then, you could just iterate thru the string and overwrite the index. Consider this example:

    $string = '5-2-1-otherTitle';
    $string = str_ireplace('-', '', $string);
    $index = null;
    for($x = 0; $x < strlen($string); $x++) {
        if(is_numeric($string[$x])) {
            $index = $x;
        }
    }
    
    echo $index; // outputs 2
    
    // works
    // echo preg_match_all("/[0-9]/", $string) - 1;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用