Home » Php » php – preg_replace all but numbers, letters, periods, and slash?

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

Posted by: admin July 12, 2020 Leave a comment

Questions:

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);
How to&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);

Answer:

To be unicode compatible you can use:

$targetFile = preg_replace('#[^\pL\pN./-]+#', '', $targetFileDirty);

Answer:

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