2016-05-29 2 views
2

У меня есть этот PHP код:PHP удалить все символы перед, за исключением последнего номера

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

Я хочу только номер 1139. Но я не могу найти, как это сделать с preg_replace. Я сделал несколько рисунков, но я не могу делать то, что хочу ..

Может кто-нибудь мне помочь?

+0

Вы также можете получить последний номер в строке [так] (https://eval.in/578880), поставив жадную точку раньше и используя lo okbehind в качестве левой границы: ['. * (?

ответ

3

Всегда легче разрушить проблему на более мелкие детали.

Ваша проблема заключается в «найти последнее число в строке».

Я предлагаю разбить его на:

  1. Найти все числа в строке
  2. Возьмите последний

Для этого, попробуйте следующее:

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

Готово! Посмотрите, как проблемы становятся легче, когда вы их разрушаете?

+0

Это будет лучший ответ. +1 –

1

Наилучший подход к вашему вопросу, как показано ниже

$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. 
+0

Это прекрасный пример того, как все становится сложнее, если вы пытаетесь сделать все за один выстрел, а не разрушить проблему;) –

+0

@NiettheDarkAbsol :) Верьте в то, что у вас больше. –