3

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

0

5 Answers 5

8

No need for regular expressions:

$parts = explode('_', $filename);
$num = (int)end($parts);

This will explode the filename into parts based on the underscore. Then convert the last item to an int value (quick way to remove the extension).

Sign up to request clarification or add additional context in comments.

Comments

3

Try this:

preg_replace("/.*\_(\d+)(\.[\w\d]+)?$/", "$1", $filename)

5 Comments

Edited to support only letters and numbers on the extension. Also made the extension optional.
Don't try this at home kids. :)
@poojan Can you explain what you did. It seems like you changed it.
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.
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.
2

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];

Comments

2

If the number always appears after the last underscore you should use:

$underArr=explode('_', $filename);
$arrSize=count($underArr)-1;
$num=$underArr[$arrSize];
$num=str_replace(".ext","",$num);

Comments

2
$pattern = '#.*\_([0-9]+)\.[a-z]+$#';
$subject = 'whatever_files_123456.ext';
$matches = array();

preg_match($pattern, $subject,$matches);

echo $matches[1]; // this is want u want

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.