简体   繁体   中英

how to extract a certain digit from a String using regular expression in php?

I have a String (filename): s_113_2.3gp

How can I extract the number that appears after the second underscore? In this case it's ' 2 ' but in some cases that can be a few digits number.

Also the number of digits that appears after the first underscore can vary so the length of this String is not constant.

You can use a capturing group:

preg_match('/_(\d+)\.\w+$/', $str, $matches);
$number = $matches[1];

\\d+ represents 1 or more digits. The parentheses around that capture it, so you can later retrieve it with $matches[1] . The . needs to be escaped, because otherwise it would match any character but line breaks. \\w+ matches 1 or more word characters (digits, letters, underscores). And finally the $ represents the end of the string and "anchors" the regular expression (otherwise you would get problems with strings containing multiple . ).

This also allows for arbitrary file extensions.

As Ωmega pointed out below there is another possibility, that does not use a capturing group. With the concept of lookarounds, you can avoid matching _ at the start and the \\.\\w+$ at the end:

preg_match('/(?<=_)\d+(?=\.\w+$)/', $str, $matches);
$number = $matches[0];

However, I would recommend profiling, before applying this rather small optimization. But it is something to keep in mind (or rather, to read up on!).

Using regex lookaround it is very short code:

$n = preg_match('/(?<=_)\d+(?=\.)/', $str, $m) ? $m[0] : "";

...which reads: find one or more digits \\d+ that are between underscore (?<=_) and period (?=\\.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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