preg_replace all but numbers, letters, periods, an

2019-02-09 17:08发布

问题:

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

回答1:

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



回答2:

To be unicode compatible you can use:

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


回答3:

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