user1392897
user1392897

Reputation: 851

Preg_replace everything after dashes with nothing PHP

I have text that looks like this:

$file = "file name-1-03-08-2014_15:56:06.doc";

For display purposes, I want to to display just "file name.doc".

So replace everything after the first dash with nothing. I believe I should use preg_replace but am not sure what the pattern would be. Is preg_replace the best function for this?

I can change the file name format to make it easier if necessary.

Upvotes: 0

Views: 736

Answers (2)

sinisake
sinisake

Reputation: 11328

$file = "file name-1-03-08-2014_15:56:06.doc";
$clean=substr_replace ($file ,'' , strpos($file,'-'),strrpos($file,'.')- strpos($file,'-')  );
echo $clean;

No regex solution, just in case...

Upvotes: 0

Alexander O'Mara
Alexander O'Mara

Reputation: 60527

You can definitely do this with a regex.

preg_replace('/-.*(\..*)$/', '$1', $file);

This regular expressions /-.*/ will match - and all characters after it .*. The file extension is captured in the parenthetic statement (\..*) with the $ requiring the extension is match at the end of the string. The second argument replaces the matched string with the match extension.

Upvotes: 2

Related Questions