How to return only the necessary match with preg_match

I am trying to parse an integer from a uris list as follows:

uri.com/upload/123456789_abc.ext

I am using this template:

preg_match( "#uri\.com\/upload\/(.*?)_#is", $uri, $match );

What works and returns:

Array
(
    [0] => uri.com/upload/123456789_
    [1] => 123456789
)

But I was wondering if there is a way to make $ match == "123456789" instead of returning an array with multiple values.

Is it possible to do this only by changing the template?

+3
source share
2 answers

It will always return an array, but you can change the template so that it matches only what you want.

$uri = "uri.com/upload/123456789_abc.ext";
preg_match('#(?<=uri\.com/upload/)\d+#is', $uri, $match );
print_r($match);

returns

Array ([0] => 123456789)

so it is still an array, but it only contains a complete match, i.e. your number.

(?<=uri\\.com/upload/) is lookbehind, it does not match this part, so it is not part of the result.

\d+ , _ .

+5

php. , perl , $1, $2, . $1 .

, , , . perl..: -)

0

All Articles