php regular expression how do i get last part of a

2019-03-01 03:23发布

问题:

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

回答1:

Try this:

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


回答2:

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



回答3:

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


回答4:

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


回答5:

$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