关于文件名和数字的PHP正则表达式 - preg_replace_callback

时间:2013-02-26 11:01:45

标签: php regex

如何捕获和提交文件名

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

3 个答案:

答案 0 :(得分:1)

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);

答案 1 :(得分:1)

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);

答案 2 :(得分:0)

您也可以使用T-Regx library

pattern('/^(([^.]*?)(?:_([0-9]*))?)(?:\.|$)/')
     ->replace('name.jpg')
     ->first()
     ->callback(function (Match $m) {
          $index = $m->group(3)->matched() ? $m->group(3)->parseInt() + 1 : 1;
          return '_' . $index;
     }