【问题标题】:Match name with underscore following number匹配名称与下划线后面的数字
【发布时间】:2018-03-01 10:04:37
【问题描述】:

我有一个像“Doc 16_1.pdf”这样的文件名,我必须使用 preg_match 检查该名称是否存在,如果匹配,下一个数字将是“Doc 16_2.pdf”

'/(?:(?: \(_[\d]+\))?(\.[^.]+))?$/'

$name = 'Doc 16';

我喜欢检查

    return preg_replace_callback(
        /(?:(?: \(_[\d]+\))?(\.[^.]+))?$/,
        array($this, 'upcount_name_callback'),
        $name,
        1
    );

增加喜欢

protected function upcount_name_callback($matches) {
    print_r($matches);
    $index = isset($matches[1]) ? ((int)$matches[1]) + 1 : 1;        
    $ext = isset($matches[2]) ? $matches[2] : '';        
    $nm = '_'.$index.$ext;        
    return $nm;
}

我已经尝试了上面的 preg_match 但它没有返回匹配结果。

您能帮帮我吗,在此先感谢。

【问题讨论】:

  • 也许'~_\d+\.[^.]+$~' 可以吗?
  • 样本输入是什么,期望的输出是什么?
  • 你能举一些例子吗?我不确定我是否正确
  • 您使用的不是preg_match,而是preg_replace_callback
  • 你必须在哪里检查它是否真的存在?如果您正在查看目录,那么简单的答案就是 file_exists

标签: php regex preg-match preg-replace-callback


【解决方案1】:

以此为起点。

<?php
if (preg_match("/^(.*)_(\d*)\.pdf$/", $filename, $output)) {
    $docname = $output[1];
    $num = (int)$output[2];
}
?>

例如http://www.phpliveregex.com/p/lns

【讨论】:

    【解决方案2】:

    您可以使用增加数字

    preg_replace_callback('/_(\d+)(\.[^.]+)?$/', function($m) {
        return "_" . ($m[1]+1) . $m[2];
    },$name);
    

    详情

    • _ - 下划线
    • (\d+) - 第 1 组 ($m[1]):一位或多位数字
    • (\.[^.]+)? - 可选组 2 ($m[2]):一个点和 1 个或多个除 . 之外的字符
    • $ - 字符串结束。

    PHP demo

    $name = 'Doc 16_1.pdf';
    echo preg_replace_callback('/_(\d+)(\.[^.]+)?$/', function($m) {
        return "_" . ($m[1]+1) . $m[2];
    },$name);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-26
      • 1970-01-01
      • 2014-09-19
      • 2011-01-04
      • 2020-08-26
      • 1970-01-01
      • 2017-10-16
      • 1970-01-01
      相关资源
      最近更新 更多