PHP remove non alphanumeric characters from string

In many cases there will be a requirement to remove non alphanumeric characters from string.
The cases can be filtering the user input data, displaying only alphanumeric content, filtering the data for inserting in to database etc.

If the requirement is to allow only alphanumeric characters from the user input and remove non alphanumeric characters from string, the below function is the right way to move on.

 

function onlyAlphanumeric($string) {
		if (!is_array($string)) {
			return preg_replace("/[^a-zA-Z0-9]/", '', $string);
		}
// in string is array
		$cleaned_string = array();
		foreach ($string as $key => $value) {
			$cleaned_string[$key] = preg_replace("/[^a-zA-Z0-9]/", '', $value);
		}

		return $cleaned_string;
	}

This onlyAlphanumeric function not only remove non alphanumeric characters form string but also removes from array.

By modifying the function we can allow an array of additional characters that are not to be removed from the string or array.

 

function onlyAlphanumeric($string, $allowed_characters = array()) {
		$allow = '';
		if (!empty($allowed_characters)) {
			foreach ($allowed_characters as $character) {
				$allow .= "\\$character";
			}
		}

		if (!is_array($string)) {
			return preg_replace("/[^{$allow}a-zA-Z0-9]/", '', $string);
		}
// if string is array
		$cleaned_string = array();
		foreach ($string as $key => $value) {
			$cleaned_string[$key] = preg_replace("/[^{$allow}a-zA-Z0-9]/", '', $value);
		}

		return $cleaned_string;
	}

$allowed_characters in the above function should be an array.

Example:

$allowed_characters = array(‘!’, ‘ ‘);

$string = “Hello @#$% World!”;

echo  onlyAlphanumeric($string,$allowed_character);

// output Hello  World!

 

Leave a Reply

Your email address will not be published. Required fields are marked *