PHP删除前面的所有字符,最后一个数字除外

PHP删除前面的所有字符,最后一个数字除外,php,preg-replace,Php,Preg Replace,我有以下php代码: $test = "http://cp.dmbshare.net:8000/hls/niehaus/niehaus/1822/1822_1139.ts"; 我只想要号码1139。但我找不到如何处理preg_替换。 我做了一些图案,但我不能做我想做的 有人能帮我吗 把问题分解成更小的部分总是比较容易的 preg_match('/(\d+)\.ts$/', $test, $matches); echo $matches[1]; 您的问题是“查找字符串中的最后一个数字” 我建议

我有以下php代码:

$test = "http://cp.dmbshare.net:8000/hls/niehaus/niehaus/1822/1822_1139.ts";
我只想要号码
1139
。但我找不到如何处理preg_替换。 我做了一些图案,但我不能做我想做的


有人能帮我吗

把问题分解成更小的部分总是比较容易的

preg_match('/(\d+)\.ts$/', $test, $matches);
echo $matches[1];
您的问题是“查找字符串中的最后一个数字”

我建议将其分为:

  • 查找字符串中的所有数字
  • 拿最后一个
  • 为此,请尝试以下方法:

    // match all numeric substrings
    preg_match_all("/\d+/",$test,$matches);
    // all matches are in $matches[0]
    // get last:
    $lastnumber = array_pop($matches[0]);
    
    完成了!看看当你把问题分解时,问题是如何变得容易的

    解决您的问题的最佳方法如下所示

    解释


    这是一个完美的例子,说明如果你试图一次完成所有事情而不是解决问题,事情会变得过于复杂;)@NiettheDarkAbsol:)相信拥有更多。这将是最好的答案+1您还可以通过在前面放置贪心点并使用lookback作为左边框来获取行中的最后一个数字:。
    $test = "http://cp.dmbshare.net:8000/hls/niehaus/niehaus/1822/1822_1139.ts";
    
    $test = preg_replace("/(?:.*)((?:\_)([0-9]+))(?:\.[a-z0-9]+)$/","$2",$test);
    
    echo $test; // 1139
    
    (
        ?: Non-capturing group. Groups multiple tokens together without creating a capture group.
        . Dot. Matches any character except line breaks.
        * Star. Match 0 or more of the preceding token.
    )
    (
        Capturing group #1. Groups multiple tokens together and creates a capture group for extracting a substring or using a backreference.
        (
            ?: Non-capturing group. Groups multiple tokens together without creating a capture group.
            \_ Escaped character. Matches a "_" character (char code 95).
        )
        (
            Capturing group #2. Groups multiple tokens together and creates a capture group for extracting a substring or using a backreference.
            [ Character set. Match any character in the set.
            0-9 Range. Matches a character in the range "0" to "9" (char code 48 to 57).
            ]
            + Plus. Match 1 or more of the preceding token.
        )
    )
    (
        ?: Non-capturing group. Groups multiple tokens together without creating a capture group.
        \. Escaped character. Matches a "." character (char code 46).
        [ Character set. Match any character in the set.
        a-z Range. Matches a character in the range "a" to "z" (char code 97 to 122).
        ]
        + Plus. Match 1 or more of the preceding token.
    )
    $ End. Matches the end of the string, or the end of a line if the multiline flag (m) is enabled.