user547794
user547794

Reputation: 14511

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);

Upvotes: 7

Views: 23715

Answers (3)

Toto
Toto

Reputation: 91385

To be unicode compatible you can use:

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

Upvotes: 7

Christopher
Christopher

Reputation: 774

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

Upvotes: 2

Michael Low
Michael Low

Reputation: 24506

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);

Upvotes: 23

Related Questions