Filtering ascii control characters with php tips

  • 2021-06-28 11:30:40
  • OfStack

Remember that at work, you imported data from other websites you crawled to xml.However, you will encounter one problem: the page will have ascII control characters.1 Start thinking someone else joined to prevent collection, and then add one to the filter table if you find one.They were all characters in the ascii table until they were slowly discovered.If you find the reason, you can solve it.


/** 
 *  according to ascii Code filter control characters  
 * @param type $string 
 */
public static function special_filter($string) 
{ 
 if(!$string) return ''; 

 $new_string = ''; 
 for($i =0; isset($string[$i]); $i++) 
 { 
  $asc_code = ord($string[$i]);    // Get it asc code  

  // The following code is designed to filter illegal characters  
  if($asc_code == 9 || $asc_code == 10 || $asc_code == 13){ 
   $new_string .= ' '; 
  } 
  else if($asc_code > 31 && $asc_code != 127){ 
   $new_string .= $string[$i]; 
  } 
 } 

 return trim($new_string); 
}


Related articles: