tags:

views:

96

answers:

4

How can I exclude @ # $%^&* from a given string?

+1  A: 

Try this:

$str= preg_replace("/[^a-zA-Z0-9_\-\/=]+/", "", 'your string here');

This allows only common acceptable chars. Excludes the chars you mentioned.

Or you can try this too:

$str = '@ # $%^&*';
$new_str = str_replace(array('@', '#', '$', '%', '^', '&', '*'), '', $str);
print $new_str;
Sarfraz
You don’t need to escape the `.` and `?` inside a character class.
Gumbo
@ Gumbo: corrected it :)
Sarfraz
+5  A: 

You can specify multiple characters to replace using str_replace:

$s= 'what a @bad #$%^ string *';
$s= str_replace(array('@', '#', '$', '%', '^', '%', '*'), '', $s);
echo($s);

This will ouput:

what a bad  string
pygorex1
+1  A: 
$thisIsaVeryBadStringIndeed = "@wh#at %a b^a&d @#$%^&*string";
$unWantedBadCharacters = "@#$%^&*";

$chars = preg_split('//',$unWantedBadCharacters);

for ($i=0;$i<strlen($unWantedBadCharacters);++$i)
    $pairs[$unWantedBadCharacters{$i}] = '';

$stringWithoutBadCharacters = strtr($thisIsaVeryBadStringIndeed,$pairs);

This is one of the faster methods. If you only create the pairs array once.

Peter Lindqvist
Oh and yes, i know i am not replacing individual characters. Was that really the question?
Peter Lindqvist
+1, shouldn't downvote b/c question was vague!
pix0r
Peter Lindqvist
Flins
Roger that.. I've adjusted.
Peter Lindqvist
+5  A: 

A simple regular expression would be one way to do it:

$str = preg_replace('/[@#$%^&*]/', '', $str);
Lukáš Lalinský
Using regex here is like using a cannon to kill a fly.
Alix Axel
Is it? It's shorter to write and faster to execute that any other way I can think of.
Lukáš Lalinský
Faster than a simple `str_replace()` or a `strtr()`?
Alix Axel
Yes, definitely.
Lukáš Lalinský
@Lukáš: +1 You're right, sorry. I benchmarked it and it's `preg_replace()` is slightly faster due to the slow array instantiation on `str_replace()` and `strtr()`.
Alix Axel
It depends on how you benchmark and on what platform i guess. For me the `strtr()` is actually the fastest.
Peter Lindqvist