0

I know I can convert the filename from .xlsx to .csv like this:

$pFileName = "hello.xlsx"
str_replace(".xlsx", ".csv", $pFileName);

... and convert .xls to .csv like this:

$pFileName = "hello.xls"
str_replace(".xls", ".csv", $pFileName);

My question is, how can I make a single function that converts my filename to .csv if its .xlsx or .xls? This means, "change the file name to .csv if it's .xls or xlsx in one single (if it's possible) str_replace.

I tried with a double str_replace with no luck:

str_replace(str_replace(".xlsx", ".csv", $pFileName), ".csv", $pFileName)

Thanks in advance.

Avión
  • 7,963
  • 11
  • 64
  • 105

4 Answers4

4

You can pass an array to str_replace:

str_replace([".xlsx", ".xls"], ".csv", $pFileName)
rdiz
  • 6,136
  • 1
  • 29
  • 41
4

I comment to use array like:

$pfilename = "hello.xlsx";

$arr = array(".xlsx", ".xls");
echo str_replace($arr, ".csv", $pfilename); // hello.csv
3

Very simple:

str_replace(array(".xlsx", ".xls"), ".csv", $pfilename);
Jeroen Bellemans
  • 2,049
  • 2
  • 25
  • 42
3

Using preg_replace

$pFileName = "hello.xls";
echo $filename = preg_replace('"\.(xls|xlsx)$"', '.csv', $pFileName);
Saty
  • 22,443
  • 7
  • 33
  • 51