2013-02-26 33 views
2

如何捕捉和文件服務器上的文件名的文件名和數量PHP正則表達式 - 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 
+0

試試這個回報$比賽[2]。 '_'。 $ index。 ''; – sanj 2013-02-26 11:10:09

+0

這已經試過了,但它是錯誤的,例如,news_1jpg – 2013-02-26 11:14:48

回答

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

它工作。非常感謝您的幫助!我會見到你 – 2013-02-26 12:42:03

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

好吧試試這個,我改變了正則表達式 – sanj 2013-02-26 11:28:51

+0

好吧,但比其他答案更好。感謝你的回答。 – 2013-02-26 12:43:06