PHP Remove all but allowed characters or disallowed chars

The following will remove all characters but those allowed using preg_replace().

$input = '"Shall I compare thee to a summer\'s day?"';
$output = preg_replace('/[^A-Za-z0-9]/', ' ', $input);
echo 'input:  ' . $input . "\n";
echo 'output: ' . $output . "\n";
input:  "Shall I compare thee to a summer's day?"
output:  Shall I compare thee to a summer s day

Another example which replaces the delimiter character with the at symbol.

$str = preg_replace('@[^a-zA-Z0-9_:;\(\)\?\|\&=!<>+*/\%-]@', '', $str);

Common alternate delimiters: #, @, !

This post is available on GitHub.
Posted .


Leave a Reply