Web Hosting Talk







View Full Version : [PHP] best way to clean up a string?


etogre
04-11-2008, 01:44 PM
Rarely do I find myself asking for answers, but this one's throwing me for a loop.

How would you clean up a string so that it will only contain alphanumerics ([a-Z][0-9]) and only certain characters (such as: +,_,-, )

The string I am looking to cleanup can contain a vast variety of characters.

If the answer is real simple go ahead and smack me! :stickout:

eviltechie
04-11-2008, 01:49 PM
Loop through the string of characters. Attempt a regular expression match, using a pattern like /[A-Za-z0-9\+_-\ ]/, if a match is found, append it to a new string. Return the new string, which will contain only characters matching your pattern.

Chasseur d'étoiles
04-11-2008, 01:50 PM
<?php
preg_replace ("/([^A-Za-z0-9\+_\-,]+)/", "", $string);
?>

seems the best to me. Not tested tho.

[edit]
lol you got me evil by 1 minute.

eviltechie
04-11-2008, 01:52 PM
<?php
preg_replace ("/([^A-Za-z0-9\+_\-,]+)/", "", $string);
?>

seems the best to me. Not tested tho.

Yeah, that'd probably work best. Didn't even think to use replace, lol.

etogre
04-11-2008, 01:54 PM
bleh, my minds not right today I was thinking preg_replace would make me have to specify everything that I *don't* want in the string.

Thanks, I knew the answer would be something simple >.>