我有一个文件whatever_files_123456.ext
。我需要读取文件名中最后一个下划线后面的数字。文件名可能包含多个下划线,但我只关心最后一个下划线和扩展名之间的数字。在这种情况下,它是123456。
我有一个文件whatever_files_123456.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