WP-Mix

A fresh mix of code snippets and tutorials

PHP String Cleaner

Here is a PHP snippet for cleaning or sanitizing variables.

This function works great for removing unwanted characters from PHP variables. For example, if you’re using WordPress, you can add this function to your theme’s functions.php file:

// string cleaner @ https://wp-mix.com/php-string-cleaner/
function string_cleanr($string) {
	$string = trim($string); 
	$string = strip_tags($string);
	$string = htmlspecialchars($string, ENT_QUOTES, 'UTF-8');
	$string = str_replace("\n", "", $string);
	$string = trim($string);
	// if (get_magic_quotes_gpc()) $string = stripslashes($string);
	return $string;
}

Then use it anywhere in your theme to clean up input and other variables. For example, if you wanted to catch the current user-agent:

// USER AGENT
if (isset($_SERVER['HTTP_USER_AGENT'])) {
	$agent = string_cleanr($_SERVER['HTTP_USER_AGENT']);
} else {
	$agent = "undefined";
}

And so on and so forth :)

★ Pro Tip:

USP ProSAC Pro