PHP正则表达式如何获取字符串的最后一部分

3

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

5个回答

8

无需正则表达式:

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

这将根据下划线将文件名分解为部分。然后将最后一项转换为int值(快速删除扩展名的方法)。


3
尝试这个:

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

编辑以支持扩展名上的字母和数字。同时,使扩展名变为可选项。 - Poojan
不要在家尝试这个,孩子们。 :) - Jason McCreary
@poojan 你能解释一下你做了什么吗?看起来你改变了它。 - Pinkie
我已将 .. 更改为 (.[\w\d]+)? .. 将允许在扩展名后输入任何字符(包括符号)。 (.[\w\d]+)? 限制为数字和字符。同时,? 使扩展名变成可选项。 - Poojan
是的。. 是转义后的点号。[\w\d] 表示只能是 A-Za-z0-9 中的字符。[]+ 确保方括号内至少有一个或多个字符,因此它不能是空的。 - Poojan

2

如果数字总是在结尾,使用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];

2

如果数字总是出现在最后一个下划线后面,您应该使用:

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接