dsm0688 2014-07-06 14:28
浏览 34
已采纳

PHP正则表达式模式[关闭]

I'm trying to get the unique ID from a string using PHP regex but I'm having problems generating the regex pattern.

sample urls

lesson-computer-networking-xpt2-t9295779.html // need to get 9295779
lesson-summary-t9295778.html //need to get 9295778
lesson-part2-t94.html //need to get 94

The length of first portion of the string depends on the page title but last portion is always -txxxxxxxx.html

Can someone help me to generate the pattern?

  • 写回答

3条回答 默认 最新

  • dongshai8330 2014-07-06 14:34
    关注

    You could use the below regex to get the number after t which was before .html,

    -t\K\d+(?=\.html)
    

    OR

    (?<=-t).*(?=\.html)
    

    DEMO

    Your PHP code would be,

    <?php
    $data = <<<'EOT'
    lesson-computer-networking-xpt2-t9295779.html
    lesson-summary-t9295778.html
    lesson-part2-t94.html
    EOT;
    $regex = '~(?<=-t).*(?=\.html)~';
    preg_match_all($regex, $data, $matches);
    var_dump($matches);
    ?>
    

    Output:

    array(1) {
      [0]=>
      array(3) {
        [0]=>
        string(7) "9295779"
        [1]=>
        string(7) "9295778"
        [2]=>
        string(2) "94"
      }
    }
    

    Explanation:

    • (?<=-t) A lookbehind is used to look after specific pattern. In our case the regex engine should set the matching marker just after to the string -t.
    • .*(?=\.html) Next it matches all the characters upto the string .html(ie, when .html is seen by the regx engine, it suddenly stops the matching)
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 QTableWidget重绘程序崩溃
  • ¥15 51寻迹小车定点寻迹
  • ¥15 谁能帮我看看这拒稿理由啥意思啊阿啊
  • ¥15 关于vue2中methods使用call修改this指向的问题
  • ¥15 idea自动补全键位冲突
  • ¥15 请教一下写代码,代码好难
  • ¥15 iis10中如何阻止别人网站重定向到我的网站
  • ¥15 滑块验证码移动速度不一致问题
  • ¥15 Utunbu中vscode下cern root工作台中写的程序root的头文件无法包含
  • ¥15 麒麟V10桌面版SP1如何配置bonding