2010-10-01 66 views
1

我有字符串,名稱爲File_Test_name_1285931677.xmlFile是常用詞,1285931677是一個隨機數。 我想刪除File__1285931677.xml,即前綴最多爲_,後綴爲_在PHP中替換字符串

+4

你應該詳細一點加入比賽,因爲字面回答你的問題是一個平凡的'str_replace' – 2010-10-01 12:57:34

+0

是否有任何圖案或文件總是像這樣命名? – Shikiryu 2010-10-01 12:59:30

+0

我想刪除第一個字符串之前_和最後一個字符串after_ – Warrior 2010-10-01 13:07:00

回答

5

您可以explodearray_sliceimplode做到這一點:

implode('_', array_slice(explode('_', $str), 1, -1)) 

隨着explode的字符串被在_切成小塊,這樣的結果是這樣一個數組:

array('File', 'Test', 'name', '1285931677.xml') 

隨着array_slice抓住所有從第二個到第二個,例如:

array('Test', 'name') 

這是再放回一起使用implode,導致:

Test_name 

另一種方法是使用strrpossubstr

substr($str, 5, strrpos($str, '_')-5) 

由於File_有固定的長度,我們可以使用5作爲起始位置。 strrpos($str, '_')返回最後一次出現_的位置。當從該位置減去5時,我們得到從第五個字符到最後一次出現位置的距離,作爲子串的長度。

1

如果你只想要替換爲的字符串replace_string是去

$str = "File_Test_name_1285931677.xml"; 
echo str_replace("File_Test_name_1285931677.xml",'Test_name', $str); 

如果您要重命名你需要使用rename一個文件的方式:

rename("/directors_of_file/File_Test_name_1285931677.xml", "Test_name"); 
3

我會偷懶,使用:

$file_name = "File_Test_name_1285931677.xml"; 
preg_replace("/^File_Test_name_\d+\.xml$/", "Test_name.xml", $filename); 

這是提供您一直想打電話它Test_name。如果TEST_NAME變化:

preg_replace("/^File_(.+)_\d+\.xml$/", "$1.xml", $file_name); 

EDIT(再次): 重讀您的更新。你會想要第二個例子。

1
$filename = preg_replace('/^File_(.*?)_\d+\.xml$/', '$1', $filename); 
0

您也可以使用substr,但顯然與模式匹配str_replace函數會更好:

$file = "File_test_name_12345.xml"; 
$new_file = substr($file,strpos($file,'_')+1,strrpos($file,'_')-strpos($file,'_')).substr($file,strrpos($file,'.')); 
+0

而人們說正則表達式是不可讀的:) – 2010-10-01 13:33:27