String Replace in PHP
I have string named File_Test_name_1285931677.xml
. File
is the common word and 1285931677
开发者_如何学运维is a random number.
I want to remove File_
and _1285931677.xml
, i.e. prefix up to first _
and suffix from last _
on.
You can do this with explode
, array_slice
and implode
:
implode('_', array_slice(explode('_', $str), 1, -1))
With explode
the string gets cut into parts at _
so that the result is an array like this:
array('File', 'Test', 'name', '1285931677.xml')
With array_slice
everything from the second to the second last is grabbed, e.g.:
array('Test', 'name')
This is then put back together using implode
, resulting in:
Test_name
Another approach would be to use strrpos
and substr
:
substr($str, 5, strrpos($str, '_')-5)
Since File_
has fixed length, we can use 5 as the starting position. strrpos($str, '_')
returns the position of the last occurrence of _
. When subtracting 5 from that position, we get the distance from the fifth character to the position of the last occurrence that we use as the length of the substring.
I would be lazy and use:
$file_name = "File_Test_name_1285931677.xml";
preg_replace("/^File_Test_name_\d+\.xml$/", "Test_name.xml", $filename);
This is provided you always want to call it Test_name. If Test_name changes:
preg_replace("/^File_(.+)_\d+\.xml$/", "$1.xml", $file_name);
EDIT (Again): Reread your update. You'll want the second example.
If you only want to replace as string replace_string is the way to go
$str = "File_Test_name_1285931677.xml";
echo str_replace("File_Test_name_1285931677.xml",'Test_name', $str);
If you want to rename a file you need to use rename:
rename("/directors_of_file/File_Test_name_1285931677.xml", "Test_name");
$filename = preg_replace('/^File_(.*?)_\d+\.xml$/', '$1', $filename);
You could also use substr but clearly a str_replace with pattern matching would be better:
$file = "File_test_name_12345.xml";
$new_file = substr($file,strpos($file,'_')+1,strrpos($file,'_')-strpos($file,'_')).substr($file,strrpos($file,'.'));
精彩评论