Sreedevi
Sreedevi

Reputation: 107

Remove special characters from string except dot - PHP

I am using phpseclib SSH command to delete uploaded file in server. The file names with spaces are difficult to delete. So I am trying to remove spaces for filenames before upload.

I have used $file_name = preg_replace('/\s+/', '', $filename); It removes white spaces but special characters also making problem to delete.

So I have used this code to remove special characters preg_replace('/[^A-Za-z0-9\-]/', '.', $filename);

But this code removes . also. file.zip becomes filezip. I want to remove special characters along with spaces except dot symbol. Pls help

Upvotes: 0

Views: 1049

Answers (1)

Gurpreet Kait
Gurpreet Kait

Reputation: 36

I have also tried it with in-built functions but it was not working. After that I have tried some different codes, I hope they will help you. And if not then try to customize it to get the desired result.

$filename = 'file(1).zip';


$checking_extension_index = strrpos($filename, '.'); // == it will return extension words after dot which will be extension name
echo '<br> ' . $file_name =  preg_replace('/[^A-Za-z0-9\-]/', '', $filename);
echo 'extension name will be : - ' . $extension_name = substr($filename, $checking_extension_index); // Extracting extension name after dot
echo '<br>' . $full_file_name = $file_name . $extension_name;```

Upvotes: 2

Related Questions