我有一个文件whatever_files_123456.ext
。我只需要读取文件名中最后一个下划线后面的数字。文件名可以包含多个下划线。我只关心最后一个下划线之后和。ext之前的数字。在本例中是123456
不需要正则表达式:
$parts = explode('_', $filename);
$num = (int)end($parts);
这将根据下划线将文件名分解为部分。然后将最后一项转换为int值(快速删除扩展名的方法)。
试试这个:
preg_replace("/.*'_('d+)('.['w'd]+)?$/", "$1", $filename)
如果数字在末尾总是,那么使用explode
通过下划线分隔名称,从列表中获取最后一项,并去掉".ext"可能会更快。如:
<?php
$file = 'whatever_files_123456.ext';
$split_up = explode('_', $file);
$last_item = $split_up[count($split_up)-1];
$number = substr($last_item, 0, -4);
但是,如果您确实想使用preg_match,则可以这样做:
<?php
$file = 'whatever_files_123456.ext';
$regex = '/_('d+).ext/';
$items = array();
$matched = preg_match($regex, $file, $items);
$number = '';
if($matched) $number = $items[1];
如果数字总是出现在最后一个下划线之后,则应使用:
$underArr=explode('_', $filename);
$arrSize=count($underArr)-1;
$num=$underArr[$arrSize];
$num=str_replace(".ext","",$num);
$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