note 113925 added to function.iconv

From: Date: Wed, 18 Dec 2013 05:16:38 +0000
Subject: note 113925 added to function.iconv
Groups: php.notes 
Request: Send a blank email to php-notes+get-197967@lists.php.net to get a copy of this message
A function to convert UTF-8 to best-fit ASCII. Handles punctuation too. Characters it doesn't understand get converted to '?'. <?php function utf8_to_ascii($text) { if (is_string($text)) { // Includes combinations of characters that present as a single glyph $text = preg_replace_callback('/\X/u', __FUNCTION__, $text); } elseif (is_array($text) && count($text) == 1 && is_string($text[0])) { // IGNORE characters that can't be TRANSLITerated to ASCII $text = iconv("UTF-8", "ASCII//IGNORE//TRANSLIT", $text[0]); // The documentation says that iconv() returns false on failure but it returns '' if ($text === '' || !is_string($text)) { $text = '?'; } elseif (preg_match('/\w/', $text)) { // If the text contains any letters... $text = preg_replace('/\W+/', '', $text); // ...then remove all non-letters } } else { // $text was not a string $text = ''; } return $text; } $text = 'Française señor café 0123 කොහොමද ශ්‍රී ලංකා hello Žluťoučký kůň ' . 'ÀÁÂ,ÃÄÅ,Æ,ÇÈ,ÉÊË,ÌÍÎ,ÏÐÑ,ÒÓÔ,ÕÖØ,ÙÚÛ,ÜÝ,Þ,' . 'ß,àáâ,ãäå,æ,çèé,êëì,íîï,ðñò,óôõ,öøù,úûýý,þ,ÿŔŕ ' . 'YA(亚) HE(何) Tra Mỹ'; print(utf8_to_ascii($text)); /* prints Francaise senor cafe 0123 ???? ?? ?? hello Zlutoucky kun AAA,AAA,AE,CE,EEE,III,IDN,OOO,OOO,UUU,UY,Th, ss,aaa,aaa,ae,cee,eei,iii,dno,ooo,oou,uuyy,th,yRr YA(?) HE(?) Tra My */ ?> ---- Server IP: 72.52.91.14 Probable Submitter: 72.52.91.14 ---- Manual Page -- http://php.net/manual/en/function.iconv.php Edit -- https://master.php.net/note/edit/113925 Del: integrated -- https://master.php.net/note/delete/113925/integrated Del: useless -- https://master.php.net/note/delete/113925/useless Del: bad code -- https://master.php.net/note/delete/113925/bad+code Del: spam -- https://master.php.net/note/delete/113925/spam Del: non-english -- https://master.php.net/note/delete/113925/non-english Del: in docs -- https://master.php.net/note/delete/113925/in+docs Del: other reasons-- https://master.php.net/note/delete/113925 Reject -- https://master.php.net/note/reject/113925 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#197967) next »