[英]How to increment a filename suffix in php
我對正則表達式和在php中使用字符串的理解充其量是最差的,因此,如果這對大多數人來說都是一個簡單的問題,我深表歉意。 如果老實說,我所做的搜索使我感到困惑,希望這里的人可以給我一個明確的答案。
我只需要增加PHP中文件名的后綴即可。
文件名如下所示:
13132432343243432434234_1.jpg
我希望文件名保持原樣,但將最后的“ _1”部分替換為“ _2”,“ _ 3”,“ _ 4”等。
無需檢查文件是否存在,這需要簡單的字符串操作。 如果后綴是_1,則將其替換為_2,如果后綴是_4,則將其替換為_5等。
提前致謝。
遵循以下原則即可:
echo preg_replace_callback('/(?<=_)\d+(?=\.)/',
function ($m) { return ++$m[0]; },
'13132432343243432434234_1.jpg');
正則表達式匹配“任何以_
開頭和后跟.
” ,回調函數返回此數字加1。
您也可以使用簡單的字符串函數,而無需使用正則表達式:
$filename = '13132432343243432434234_1.jpg';
// Splits into '13132432343243432434234_1' and '.jpg'
list($name, $ext) = explode('.', $filename);
// Splits into '13132432343243432434234' and '1'
list($basename, $index) = explode('_', $name);
$index++; // increment the index
$filename = $basename . '_' . $index . '.' . $ext;
這應該做的工作。
<?php
$file = "13132432343243432434234_1.jpg"; // old filename
list ($fn,$ext) = preg_split("/\./",$file); // split name and extension
print_r(array($fn,$ext));
list($pre,$suffix) = preg_split("/_/",$fn); // split prefix and suffix
print_r(array($pre,$suffix));
$suffix++; // increment by 1
$file = $pre . "_" . $suffix . $ext; // regroup
echo "NEW FILENAME: " . $file; // new filename
?>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.