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 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算