PHP5 String Cleaner

31 August, 2007 (22:38) | PHP

Sometimes it’s handy to have a simple, easy to use string cleaning class for those times you need to use a string from an untrusted source, such as a URL or Form Input.

Here’s a snippet that’ll do the job. It will only return Alphanumeric Characters, but also allows Asterisk, Underscore, Period and Dash (pretty well harmless in SQL). You should still check your SQL before using it to query a database, however.


/**
 * @package core
 * @subpackage strings
 */

class StringHandler {

	public function __construct() {

	}

	public function cleanString($string) {
	   return ereg_replace("[^[:space:]a-zA-Z0-9*_.-]", "", $string);
	}
}

You can use it like this: StringHandler::cleanString($stringToBeCleaned);

Write a comment