简体   繁体   English

PHP删除之前的所有字符,除了最后一个数字

[英]PHP remove all characters before, except last number

I have this php code: 我有这个PHP代码:

$test = "http://cp.dmbshare.net:8000/hls/niehaus/niehaus/1822/1822_1139.ts";

I want only number 1139 . 我只想要号码1139 But I can't find how to do with preg_replace. 但我找不到如何处理preg_replace。 I made some pattern, but I can't do what I want.. 我做了一些模式,但我不能做我想要的......

Can anybody help me? 有谁能够帮助我?

preg_match('/(\d+)\.ts$/', $test, $matches);
echo $matches[1];

It's always easier to break down a problem into smaller parts. 将问题分解成更小的部分总是更容易。

Your problem is "find the last number in the string". 你的问题是“找到字符串中的最后一个数字”。

I propose breaking it down into: 我建议把它分解成:

  1. Find all numbers in the string 查找字符串中的所有数字
  2. Take the last one 拿最后一个

To that end, try this: 为此,试试这个:

// match all numeric substrings
preg_match_all("/\d+/",$test,$matches);
// all matches are in $matches[0]
// get last:
$lastnumber = array_pop($matches[0]);

Done! 完成! See how problems get easier when you break them down? 了解如何在分解问题时更容易解决问题?

The best approach to your question is as below 您问题的最佳方法如下

$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

Explaination

(
    ?: 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.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM