0

I want to replace all characters except 'A-Z','a-z','0-9', '_', '-', '(', ')' from a filename, until the extension.

For the moment i have:

$filename = '23$%^&.234234.%^.234$%$#)(.^$.png';

$fileName = preg_replace('/[^A-Za-z0-9_\-\(\) ]/', '-', $filename);

and i get

$filename : 23------234234----234----)(----png

The problem is that the '.' from extension is removed. The filename can have different extension.

How should i make to change the characters, but not the extension.

1 Answer 1

1

You can try with pathinfo function to separate extension from filename and replace unwanted character only in base filename. After everything, just merge those parts:

$filename = '23$%^&.234234.%^.234$%$#)(.^$.png';
$pathinfo = pathinfo($filename);
$filename = implode('.', array(
  preg_replace('/[^A-Za-z0-9_\-\(\) ]/', '-', $pathinfo['filename']),
  $pathinfo['extension']
));

var_dump($filename);

Output:

string '23-----234234----234----)(---.png' (length=33)
Sign up to request clarification or add additional context in comments.

1 Comment

+1... but let's let him know that (as you know) /[^A-Za-z0-9_\-\(\) ]/ can be compressed to a tidy ~[^\w() -]i~ :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.