Link to home
Start Free TrialLog in
Avatar of OmniUnlimited
OmniUnlimitedFlag for United States of America

asked on

Help with preg_match()

Hello Experts!

Can anyone tell me how I could set up preg_match($pattern, $subject, $matches) to be able to capture only the digits between an underscore character ("_") and an image extension (".jpg" for example)?  In other words, let's say I have an image labeled "img_20131009_12.jpg".  How would I be able to make it so that $matches[0] contains "12"?
SOLUTION
Avatar of Ray Paseur
Ray Paseur
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Avatar of mvidas
mvidas
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
It will depend on your test data, but this shows how you might do it with the regular expression.  Look in $mat[1] instead of [0].

<?php // RAY_temp_omniunlimited.php
error_reporting(E_ALL);

$str = 'img_20131009_12.jpg';

$rgx
= '#'         // REGEX DELIMITER
. 'img_'      // LITERAL STRING
. '\d{8}'     // EIGHT DIGITS
. '_'         // LITERAL STRING
. '('         // START CAPTURE GROUP
. '[^.]{1,3}' // ANYTHING BUT DOT, UP TO THREE
. ')'         // END GROUP
. '#'         // REGEX DELIMITER
;

preg_match($rgx, $str, $mat);
var_dump($mat);

Open in new window

Avatar of OmniUnlimited

ASKER

Outstanding gentlemen!  The perfect answers in record time!

@Ray: As always, you astound me with your intimate knowledge of PHP.  Thank you for your more efficient solution.  But, since the question asked for help with preg_match, I'm afraid it is only fair to award mvidas the lion's share of the points for correctly answering the question.

@mvidas: Works like a charm.  Thanks!
Glad to have helped! FYI, if you want to extract more data (like the date, extension, etc), you can surround that area with parenthesis to create another submatch.
If your pattern is  /^img_(\d{8})_(\d+).([a-z0-9])+$/i    then your $matches would be
[0] img_20131009_12.jpg
[1] 20131009
[2] 12
[3] jpg

You can of course change that however needed if you want to further break it down.
Matt
Wow mvidas, that info is also very helpful!

Sorry I don't have any more points to award... :(
Don't be sorry at all, just glad I could help :)