1

I am working on a rename function to get rid of non alphanumeric chars in a file name.

After some searching in the forums I found a good solution to get rid of those chars but it doesn't seem to work for me.

echo $filename."\n";
$newfilenamecorrect=preg_replace("/^[a-z0-9A-Z.-_]+$/", '',$filename);
$newfilenamecorrect=dirname($path). '/' . $newfilenamecorrect;
echo $newfilenamecorrect."\n";

Where $filename is the filename itself (example Picture.jpg), $path - is the original path + filename (example ./galleries/Picture.jpg) $newfilenamecorrect Should be the new filename including path and filename.

No idea why but when I run that I get echoes like:

000���5.jpg ./galleries/iPhone/000���5.jpg
2D-Art-Iataândesson-Cruz-Gnomon.jpg ./galleries/iPhone/2D-Art-Iataândesson-Cruz-Gnomon.jpg

I'm kinda new to php, so sorry for any stupid mistakes I've made :)

  • 1
    Try `"/[^\w.-]+/u"` – Wiktor Stribiżew Jan 22 '17 at 21:49
  • http://stackoverflow.com/questions/840948/stripping-everything-but-alphanumeric-chars-from-a-string-in-php?rq=1 –  Jan 22 '17 at 21:56
  • @WiktorStribiżew: not sure, once you use the u modifier, you extend the `\w` character class to unicode, and I think that Shachar Adar looks for only ascii alnum. I suggest: `/[^0-9a-z_.-]/iu` or `/(*UTF8)[^\w.-]/` – Casimir et Hippolyte Jan 22 '17 at 22:07
  • remove the start ^ and end $ chars => /[a-z0-9A-Z.-_]+/ – DeepBlue Jan 22 '17 at 22:40
  • @nogad thanks that actually solved my problem! I used `$newfilenamecorrect=preg_replace("/[^a-z0-9._-]+/i", '',$filename);` instead of `$newfilenamecorrect=preg_replace("/^[a-z0-9A-Z.-_]+$/", '',$filename);` I have no idea why the original didn't work. – Shachar Adar Jan 23 '17 at 05:06

0 Answers0