2

如何捕获和归档文件名

我已经尝试在 PHP 中使用preg_replace_callback,但我不知道如何正确使用。

function upcount_name_callback($matches) {
   //var_export($matches);
   $index = isset($matches[3]) ? intval($matches[3]) + 1 : 1;
   return '_' . $index;
}

$filename1 = 'news.jpg';
echo preg_replace_callback('/^(([^.]*?)(?:_([0-9]*))?)(?:\.|$)/', 'upcount_name_callback', $filename1, 1);

$filename2 = 'aw_news_2.png';
echo preg_replace_callback('/^(([^.]*?)(?:_([0-9]*))?)(?:\.|$)/', 'upcount_name_callback', $filename2, 1);

输出(错误):

array (
  0 => 'news.',
  1 => 'news',
  2 => 'news',
  3 => '1',
)

_1jpg       <= wrong - filename1

.

array (
  0 => 'aw_news_2.',
  1 => 'aw_news_2',
  2 => 'aw_news',
  3 => '2',
)

_3png      <= wrong - filename2

输出(右):

news_1       <= filename1

.

aw_news_3      <= filename2
4

3 回答 3

1

您还可以使用T-Regx 库

pattern('^(([^.]*?)(?:_([0-9]*))?)(?:\.|$)')
     ->replace('name.jpg')
     ->first()
     ->callback(function (Match $m) {
          $index = $m->matched(3) ? $m->group(3)->toInt() + 1 : 1;
          return '_' . $index;
     }
于 2019-05-09T09:38:34.513 回答
0
function my_replace_callback ($matches)
{
    $index = isset ($matches [1]) ? $matches [1] + 1 : 1;
    return "_$index";
}

$file = 'news.jpg';
$file = preg_replace_callback ('/(?:_([0-9]+))?\..*$/', 'my_replace_callback', $file);
print ($file);

$file = 'aw_news.jpg';
$file = preg_replace_callback ('/(?:_([0-9]+))?\..*$/', 'my_replace_callback', $file);
print ($file);

$file = 'news_4.jpg';
$file = preg_replace_callback ('/(?:_([0-9]+))?\..*$/', 'my_replace_callback', $file);
print ($file);

$file = 'aw_news_5.jpg';
$file = preg_replace_callback ('/(?:_([0-9]+))?\..*$/', 'my_replace_callback', $file);
print ($file);
于 2013-02-26T11:50:48.000 回答
0
function upcount_name_callback($matches) {
    $index = isset($matches[3]) ? intval($matches[3]) + 1 : 1;
    return $matches[2] . '_' . $index;
}

$filename1 = 'news.jpg';
echo preg_replace_callback('/^(([^.]*?)(?:_([0-9]*))?)(?:(\..*)|$)/', 'upcount_name_callback', $filename1);

$filename2 = 'aw_news_2.png';
echo preg_replace_callback('/^(([^.]*?)(?:_([0-9]*))?)(?:(\..*)|$)/', 'upcount_name_callback', $filename2);
于 2013-02-26T11:22:15.230 回答