• 18th, Aug 2010

PHP Handling Non-English Characters UTF8

	/**
	* Returns an string with the same length.
	* - If it is smaller than num it will fill out with the fill character.
	* - If it is larger than num it will cut the string.
	* www.unexpectedit.com
	*/
	function formatcell($data, $num, $fill=' '){
	    $data = trim($data);
		$data=str_replace(chr(13),' ',$data);
		$data=str_replace(chr(10),' ',$data);
		// translate UTF8 to English characters
		$data = iconv('UTF-8', 'ASCII//TRANSLIT', $data);
		$data = preg_replace("/[\'\"\^\~\`]/i", '', $data);

		// fill it up with spaces
    	for ($i = strlen($data); $i < $num; $i++) {
    		$data .= $fill;
    	}
    	// limit string to num characters
   		$data = substr($data, 0, $num);

		return $data;
    }

    echo formatcell("YES UTF8 String Zürich", 25, 'x'); //YES UTF8 String Zürichxxx
    echo formatcell("NON UTF8 String Zurich", 25, 'x'); //NON UTF8 String Zurichxxx

Tags: , , ,

Leave a Reply

*

© 2010 unexpected[it]. All Rights Reserved.