Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

preg_replace all but numbers, letters, periods, and slash?

I have a regular expression that strips everything but letters. numbers, and periods. How do I also add foreslashes to it?

$targetFile = preg_replace('/[^A-Za-z0-9-.]/', '', $targetFileDirty);
like image 418
user547794 Avatar asked Nov 21 '11 03:11

user547794


3 Answers

You can escape the foreslash by putting a backslash before it - $targetFile = preg_replace('/[^A-Za-z0-9-.\/]/', '', $targetFileDirty);

Alternatively, and perhaps better, you can use different delimiters instead, e.g. $targetFile = preg_replace('#[^A-Za-z0-9-./]#', '', $targetFileDirty);

like image 189
Michael Low Avatar answered Nov 08 '22 06:11

Michael Low


To be unicode compatible you can use:

$targetFile = preg_replace('#[^\pL\pN./-]+#', '', $targetFileDirty);
like image 36
Toto Avatar answered Nov 08 '22 07:11

Toto


Simply add an escaped slash: [^A-Za-z0-9-.\\/]

like image 2
Christopher Avatar answered Nov 08 '22 07:11

Christopher