PHP对文件名和数字进行Regexp-preg_replace_callback


PHP Regexp on filename and number - preg_replace_callback

如何捕获和归档文件名

我在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

您也可以使用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;
     }
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);
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);