Click to See Complete Forum and Search --> : removing characters using regular expressions


jasongr
11-02-2005, 07:48 AM
Hello

I need to write code that given a string, strips from it any of the following characters:
%, &, \, ", /, ?, ', <, >, :, *, |, ^, ,

(note that comma is also not permitted)

I know that I can achieve the following using this code

$illegalCharacters = Array("%", "&", "\\", '"', "/", "?", "'", "<", ">", ":", "*", "|", "^", ",");
foreach ($illegalCharacters as $character) {
$text = str_replace($character, '', $text);
}

This seems like a very inefficient solution
Is there a better solution, one that possibly uses regular expression?

Note
I also need to strip the * and ? character
It is critical that their usage inside a regular expression will not lead to unexpected results,
stripping more characters than allowed, or missing a few ones from the list above

any help would be appreciated
thanks in advance

NogDog
11-02-2005, 10:15 AM
<?php
$text = 'Test-%&\\"/?\'<>:*|^,-(end of test).';
echo "<p>$text</p>\n";
$text = preg_replace('/[%&\\\\"\/?\'<>:*|^,]/', '', $text);
echo "<p>$text</p>\n";
?>

ShrineDesigns
11-02-2005, 05:12 PM
^*| need to be escaped as well$text = preg_replace("/[%&\*\|\\\/\"\'\?\:<>\^,]/", '', $text);

NogDog
11-02-2005, 06:19 PM
Worked fine for me without escaping them. Within a character class ([...]) they lose there special meanings ('^' only has a special meaning within a character class if it's the first character in it).

ShrineDesigns
11-03-2005, 02:50 AM
oh i was not aware of that lol

i learned my "something new" for today lol

NogDog
11-03-2005, 08:09 AM
There's always something new to learn with regexp, in my experience. It's really its own little programming language. :)

LiLcRaZyFuZzY
11-03-2005, 08:40 AM
# i am aware of the unvalidity of the code below ;)
if("little" != "simple" && "little" == "quite cryptic and difficult"){
echo "You're right";
}else{
echo "You're crazy";
}

NogDog
11-03-2005, 08:58 AM
# i am aware of the unvalidity of the code below ;)
if("little" != "simple" && "little" == "quite cryptic and difficult"){
echo "You're right";
}else{
echo "You're crazy";
}

Yeah, it's cryptic. I guess that's why Perl hackers love it. See http://perl.plover.com/obfuscated/ if you really want some cryptic code.

LiLcRaZyFuZzY
11-03-2005, 09:03 AM
WHAA! :p that is definately...cryptic