1

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.

3
  • 4
    You should elaborate a bit adding contest, because the literal answer to your question is a trivial str_replace Commented Oct 1, 2010 at 12:57
  • Is there any pattern or the file is always named like this? Commented Oct 1, 2010 at 12:59
  • I want to remove First string Before _ and last string after_ Commented Oct 1, 2010 at 13:07

5 Answers 5

5

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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.

Comments

1

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

Comments

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

Comments

0

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,'.'));

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.