Pinkie
Pinkie

Reputation: 10256

php regular expression how do i get last part of a string

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

Upvotes: 3

Views: 1753

Answers (5)

Poojan
Poojan

Reputation: 146

Try this:

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

Upvotes: 3

Mr Coder
Mr Coder

Reputation: 8186

$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

Upvotes: 2

user975343
user975343

Reputation:

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

Upvotes: 2

imm
imm

Reputation: 5919

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

Upvotes: 2

Jason McCreary
Jason McCreary

Reputation: 72991

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).

Upvotes: 8

Related Questions