I have a file whatever_files_123456.ext. I need to read just the number after the last underscore in a filename. Filename can contain many underscores. I only care about the number after the last underscore and before the .ext. In this case it's 123456
5 Answers
Try this:
preg_replace("/.*\_(\d+)(\.[\w\d]+)?$/", "$1", $filename)
5 Comments
Poojan
Edited to support only letters and numbers on the extension. Also made the extension optional.
Jason McCreary
Don't try this at home kids. :)
Pinkie
@poojan Can you explain what you did. It seems like you changed it.
Poojan
I have changed \.. to (\.[\w\d]+)? \.. would have allowed any character after the extension (symbols and all). (\.[\w\d]+)? limits it to numbers and characters. Also ? makes the extension optional.
Poojan
Yeah. \. is the (escaped) dot. [\w\d] is a character limited to A-Za-z0-9. []+ ensures that there are one or more characters that are within square brackets. So it can't be empty.
If the number is always at the end, it could be faster to use explode to split the name up by underscores, grab the last item from the list, and strip off the ".ext". Like:
<?php
$file = 'whatever_files_123456.ext';
$split_up = explode('_', $file);
$last_item = $split_up[count($split_up)-1];
$number = substr($last_item, 0, -4);
But, if you do want to use preg_match, this would do the trick:
<?php
$file = 'whatever_files_123456.ext';
$regex = '/_(\d+).ext/';
$items = array();
$matched = preg_match($regex, $file, $items);
$number = '';
if($matched) $number = $items[1];