3

I made the user possible to change file names through a textarea, but now I'm having a regex problem.

As I see for Windows 7, these characters only are not allowed for filenames:

\ / : * ? < > |

But I stubbornly, perhaps also wisely, choose to minimize the regex to ONLY these special characters:

- _ .

All the others should have to be cut.

Can someone help me out with this regex?

preg_replace all but: A-Za-z0-9 and - _ .

I still really don't get the hang of it.

9
  • 1
    or a simple str_replace(); to replace the unneded characters with an empty string like this '' Commented Dec 4, 2012 at 15:17
  • 3
    [^A-Za-z0-9\-_.]. "anything that ISN'T one of the following..." Commented Dec 4, 2012 at 15:20
  • 1
    Have you tried anything? A google search for regex filename gives you plenty of useful results. Commented Dec 4, 2012 at 15:20
  • 1
    Marc's solution is what your looking for. Commented Dec 4, 2012 at 15:23
  • 1
    @IanOverton Althoguh it wouldn't quite work, as the '-' character would act as a range. Commented Dec 4, 2012 at 15:24

2 Answers 2

16
preg_replace('/[^A-Za-z0-9 _ .-]/', '', $filename);

The [] is a character class and the ^ negates it. So it literally matches anything other than the chars in that group.

Note that - is at the end, as it is a special range character if used elsewhere, e.g. 0-9

Sign up to request clarification or add additional context in comments.

2 Comments

should it be \. ? Dot means any character.
@ESP32 only outside "[]" as inside them you are specifying characters. So "." which means everything outside the "[]", is asumed as a character inside them.
4

Your question has the character-set pretty-much laid out already. You'll just need to plug it into preg_replace() to get it going.

Try this:

$filename = preg_replace('/[^a-zA-Z0-9_.-]/', '', $filename);

The ^ at the beginning of the character set, surrounded by [], states to not-match the list of characters. Therefore, the line can be read as "replace the characters that are not the following".

Comments

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.