开发者

PHP function to remove occurrences of certain characters from a string

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜