-1

I want to remove all the illegal character and replace the space with underscore so i use this code:

function sanitize_file_name($filename) {
    $filename = preg_replace("/([^A-Za-z0-9_\-\.]|[\.]{2})/", "", $filename);
    return basename($filename);
}

for example i have a filename like "www..//../no way" when i sanitize it, it become 'wwwno_way'.

it work to remove the other character that i want but the problem is i don't know how to replace the space with underscore at the same time using preg_replace. Is it posible? and how i can accomplish it?

Ying
  • 1,282
  • 4
  • 19
  • 34

1 Answers1

0

In preg_replace() function the second param is the param you want to get replaced with.

function sanitize_file_name($filename) {
$filename = preg_replace("/([^A-Za-z0-9_\-\.]|[\.]{2})/", "_", $filename);
return basename($filename);
}
webshifu
  • 155
  • 7
  • it make $text = 'www..//../no way'; into www_____no_way. which it suppose just www_no_way. – Ying Jun 08 '18 at 15:13
  • it is because the preg_replace is replacing every illegal character with the "_", if you want only spaces to be replaced with "_" then you'll have to use the str_replace in the final return statement after preg_replace. – webshifu Jun 08 '18 at 15:17
  • yes that is why i'm asking is it posible to use single regex to remove space and replace other character with ''. – Ying Jun 08 '18 at 15:19