Clean Text Function

I needed a way to remove non-printing and irregular ascii character. This is helpfull when controlling user name formatting or comparing two strings. The output will be the cleaned up string based on the options.

Usage: $result=text_clean(<text to be reviewed>,<optional variable>);

/*
	this function will strip all non-printing and 
	irregular ascii symbols and repetitive spaces.  
	
	Option 0: (default) leaves spaces; 
	Option 1: replaces spaces with underscores; 
	Option 2: removes all spaces.
	Option 3: removes all spaces, underscores, converts to lowercase
	
*/

function text_clean($submitted,$option=0){

	//reduces multiple spaces to single
	$excess_spaces=preg_replace('/\s\s+/', ' ',$submitted);
	
	//removes all non_printing/extended ascii characters
	$non_ascii=preg_replace('/[^\da-z ]/i', '', $excess_spaces);

	//Truncates the leading and ending spaces
	$trim_spaces=trim($non_ascii);
	
	$final=$trim_spaces;
	
	if ($option==1){
		$final=preg_replace('/\s/', '_',$trim_spaces);
	}
	if ($option==2){
		$final=preg_replace('/\s/', '',$trim_spaces);
	}
	if ($option==3){
		
		$final=str_replace('_','',$trim_spaces);
		$final=preg_replace('/\s/', '',$final);
		$final=strtolower($final);
		
	}
	return	$final;

	}

Leave a Reply

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