简体   繁体   中英

php regex replace caracters from filename until extension

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM