I need a PHP function that will take a string as input, and return the string minus all occurrences of these characters: ! * ' ( ) ; : @ & = + $ , / ? % # [ ]
Is there something already built for this purpose or can it be accomplished with regex? I'd rather not do 20 differe开发者_运维问答nt str_replace function calls on this string. Thanks!
You can use str_replace with arrays:
// $arrayOfCharsToReplace = array('!','*', ...etc
$clean = str_replace(
$arrayOfCharsToReplace,
array_fill(0, count($arrayOfCharsToReplace), ''), // array of empty strings
$unclean
);
You can also use strtr
like so:
// $arrayOfReplacements = array('!' => '', '*' => '', ...etc
$clean = strtr($unclean, $arrayOfReplacements);
$quoted = preg_quote('!*\'();:@&=+$,/?%#[]','/');
$sanitized = preg_replace('/['.$quoted.']/', '', $string);
If in general, you'd like punctuation replaced, use a regex class instead (it's shorter and readable):
$sanitized = preg_replace('/[[:punct:]]/', '', $string);
You can use strtr
(this is preferred) or preg_replace
(this is slower).
精彩评论