學習遇到問題了,請過來人給予指點
當看架構源碼時(例:ci)
遇到其中不懂的寫法身邊又沒有牛人指點該怎麼辦?
就如下邊這段代碼:當strtolower($charset) != 'utf-8'時是一種處理,非而是另一種處理為什麼那?像這樣的問題如果到論壇裡去諮詢別人可能要等半天才能解決,如果搜尋尋找的話像這樣的問題又沒法下手。苦惱中..... 我該怎麼辦呢? 希望大家給予指點筆人感激不盡。
PHP code
public function entity_decode($str, $charset='UTF-8') { if (stristr($str, '&') === FALSE) return $str; // The reason we are not using html_entity_decode() by itself is because // while it is not technically correct to leave out the semicolon // at the end of an entity most browsers will still interpret the entity // correctly. html_entity_decode() does not convert entities without // semicolons, so we are left with our own little solution here. Bummer. if (function_exists('html_entity_decode') && (strtolower($charset) != 'utf-8')) { $str = html_entity_decode($str, ENT_COMPAT, $charset); $str = preg_replace('~&#x(0*[0-9a-f]{2,5})~ei', 'chr(hexdec("\\1"))', $str); return preg_replace('~&#([0-9]{2,4})~e', 'chr(\\1)', $str); } // Numeric Entities $str = preg_replace('~&#x(0*[0-9a-f]{2,5});{0,1}~ei', 'chr(hexdec("\\1"))', $str); $str = preg_replace('~&#([0-9]{2,4});{0,1}~e', 'chr(\\1)', $str); // Literal Entities - Slightly slow so we do another check if (stristr($str, '&') === FALSE) { $str = strtr($str, array_flip(get_html_translation_table(HTML_ENTITIES))); } return $str; }
------解決方案--------------------
。。。我也不怎麼懂。幫你刷上去看看。
------解決方案--------------------
ok,首先,它這個函數是有缺陷的,
試一下:
echo entity_decode('叶','utf-8');
echo "\n";
echo html_entity_decode('叶',ENT_COMPAT,'utf-8');
叶 是 "葉"字.
所以,我覺得他把
&& (strtolower($charset) != 'utf-8')
這部分從條件裡拿掉更好一點,換句話說,能用html_entity_decode就先用,然後再處理無分號結尾的.
因為你只問了這個utf8的問題,相信你別的部分都沒啥問題,我也就不多嘴了.
看別人的代碼,可以細看,也可以粗看,
比如這個函數,如果你更關心其它地方,只要知道它是html_entity_decode一個變形版就行.
------解決方案--------------------
addslashes()
------解決方案--------------------
注釋一下了:
public function entity_decode($str, $charset='UTF-8')
{
if (stristr($str, '&') === FALSE) return $str; // 如果沒能&,直接返回
// The reason we are not using html_entity_decode() by itself is because
// while it is not technically correct to leave out the semicolon
// at the end of an entity most browsers will still interpret the entity
// correctly. html_entity_decode() does not convert entities without
// semicolons, so we are left with our own little solution here. Bummer.
// 為什麼不直接用html_entity_decode() , 因為 html_entity_decode()不直接轉換不帶分號的實體。
if (function_exists('html_entity_decode') &&
(strtolower($charset) != 'utf-8'))
{
// 如果不是utf8;
$str = html_entity_decode($str, ENT_COMPAT, $charset); //根據編碼解碼
$str = preg_replace('~&#x(0*[0-9a-f]{2,5})~ei', 'chr(hexdec("\\1"))', $str); //替換
return preg_replace('~&#([0-9]{2,4})~e', 'chr(\\1)', $str); //替換返回
}
// 如果是utf8;
// Numeric Entities 如果有數字實體則替換
$str = preg_replace('~&#x(0*[0-9a-f]{2,5});{0,1}~ei', 'chr(hexdec("\\1"))', $str);
$str = preg_replace('~&#([0-9]{2,4});{0,1}~e', 'chr(\\1)', $str);