Delphi讀取utf8格式ini及取得動態內容

使用Delphi讀取utf8格式時需使用Tmeminifile,另外動態取得的範例。

VAR SYSINI: TMemIniFile; // 讀取utf8格式的ini需使用TMemIniFile
ts:tstringlist;
i:integer;
ApplicationPath:string;
begin
// 先取得目前執行路徑
ApplicationPath := ExtractFilePath(Application.exename);
if ApplicationPath[length(ApplicationPath)] = ‘\’ then
begin
ApplicationPath := copy(ApplicationPath, 1, length(ApplicationPath) – 1);
end;
// 讀取sys.ini裡的memberid區塊並顯示值
MEMO1.Lines.Clear;
ts:=tstringlist.Create;
SYSini := TMemIniFile.Create(ApplicationPath+’\sys.ini’,TEncoding.UTF8);
if NOT (SYSini = nil) then begin
sysini.ReadSection(‘memberid’,ts);
for I:=0 TO TS.Count-1 DO BEGIN
MEMO1.Lines.Add(TS[I]);
MEMO1.LINES.Add(sysini.ReadString(‘MEMBERID’,TS[I],”));
END;
end;
ts.Free;
end;

PHP ord()函數utf8問題

早上在寫註冊機程式,不過遇到php的ord函數遇到utf8時無法運作的冏境。
找到了一個解決方式,另外寫了一個delphi xe5的ord函數比對確定無誤。

來源: phpkode

function utf8_ord($chr) {    
    $ord0 = ord($chr);    
    if ( $ord0 >= 0 && $ord0 <= 127 ) {
        return $ord0;
    }    
    if ( !isset($chr{1}) ) {
        trigger_error('Short sequence - at least 2 bytes expected, only 1 seen');
        return FALSE;
    }    
    $ord1 = ord($chr{1});
    if ( $ord0 >= 192 && $ord0 <= 223 ) {
        return ( $ord0 - 192 ) * 64 
            + ( $ord1 - 128 );
    }    
    if ( !isset($chr{2}) ) {
        trigger_error('Short sequence - at least 3 bytes expected, only 2 seen');
        return FALSE;
    }
    $ord2 = ord($chr{2});
    if ( $ord0 >= 224 && $ord0 <= 239 ) {
        return ($ord0-224)*4096 
            + ($ord1-128)*64 
                + ($ord2-128);
    }    
    if ( !isset($chr{3}) ) {
        trigger_error('Short sequence - at least 4 bytes expected, only 3 seen');
        return FALSE;
    }
    $ord3 = ord($chr{3});
    if ($ord0>=240 && $ord0<=247) {
        return ($ord0-240)*262144 
            + ($ord1-128)*4096 
                + ($ord2-128)*64 
                    + ($ord3-128);
    
    }
    
    if ( !isset($chr{4}) ) {
        trigger_error('Short sequence - at least 5 bytes expected, only 4 seen');
        return FALSE;
    }
    $ord4 = ord($chr{4});
    if ($ord0>=248 && $ord0<=251) {
        return ($ord0-248)*16777216 
            + ($ord1-128)*262144 
                + ($ord2-128)*4096 
                    + ($ord3-128)*64 
                        + ($ord4-128);
    }
    
    if ( !isset($chr{5}) ) {
        trigger_error('Short sequence - at least 6 bytes expected, only 5 seen');
        return FALSE;
    }
    if ($ord0>=252 && $ord0<=253) {
        return ($ord0-252) * 1073741824 
            + ($ord1-128)*16777216 
                + ($ord2-128)*262144 
                    + ($ord3-128)*4096 
                        + ($ord4-128)*64 
                            + (ord($c{5})-128);
    }
    
    if ( $ord0 >= 254 && $ord0 <= 255 ) { 
        trigger_error('Invalid UTF-8 with surrogate ordinal '.$ord0);
        return FALSE;
    }
    
}