Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return only needed match with preg_match

I am trying to parse a integer from a list of uris like this:

uri.com/upload/123456789_abc.ext

I am using this pattern:

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

Which works and returns:

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

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

Is it possible to do it by only modifying the pattern?

like image 475
James Harzs Avatar asked Dec 13 '25 15:12

James Harzs


1 Answers

It will always return an array, but you can change the pattern, so that it only matches 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 does only contain the whole match, that is your number.

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

\d+ is only matching digits, so the _ is not needed anymore.

like image 128
stema Avatar answered Dec 15 '25 05:12

stema



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!