0

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 different str_replace function calls on this string. Thanks!

2
  • It sounds like you need whitelisting more than blacklisting. What do you want to allow? Commented Feb 24, 2011 at 17:56
  • @chelmertz, really I just need to remove those exact characters from a string. Everything else is fair game. Commented Feb 24, 2011 at 18:11

3 Answers 3

1

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);
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

0

You can use strtr (this is preferred) or preg_replace (this is slower).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.