The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)
Content-Type: text/plain; charset="UTF-8"
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
Content-Type: text/plain; charset="UTF-8"
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
#!/bin/sh
### initialize
svnarg=""
### use encoding utf-8 as default if run "svn ci" or "svn commit".
if [ "$1" != "help" ]; then
for myarg in "$@"; do
if [ "${myarg}" = "commit" ] || [ "${myarg}" = "ci" ]; then
svnarg="--encoding utf-8"
break
fi
done
fi
### wrapper script to set umask to 027 on subversion binaries
### Note: the meaning of each umask:
### umask 002 // File permission 644. Owner can read/write. Group and Others can only read.
### umask 007 // File permission 660. Owner and Group can read/write. Others can not read or write.
### umask 027 // File permission 640. Owner can read/write. Group can read. Others can not read or write.
umask 027
### svn command
/usr/local/bin/svn.orig ${svnarg} "$@"最近身旁許多在上 irc 的朋友都問我哪個 irc client 比較好用
其實,只要問過我的,而且又是 unix like 的系統使用者時
基本上都會被我推薦 irssi 這個 command mode 的純文字 irc 程式
(啥?不知道啥是 irc ? Internet Relay Chat 的縮寫,其他請洽 Google 或 Wiki )
然後如果還有 server 的朋友,更是會被我力推 screen + irssi 的組合
好處是,可以遠端持續掛著 irc ,到哪邊都可以 ssh 進去繼續看 irc log
這樣真的很方便,也不用擔心因為沒開自己的電腦,就看不到別人的對話或別人要留給自己的訊息
不過跟太多的朋友推薦了 screen + irssi 後,卻發現一直回來問我問題
原因是... man 寫的陽春到不行,然後就吵著要鄉民教學
所以這篇文章就這麼被誕生了,也順便當我的備忘錄吧 :P
以下是針對我操作時會遇到的問題整理一下
irssi 的程式安裝我就不詳細講了
apt-get or yum 裡面可以直接打撈到
先在這邊釐清第一次使用 screen + irssi 上 irc 的朋友們觀念
請先搞清楚說遇到的問題跟操作,該是由 screen 還是由 irssi 的程式部份來處理
或者本身只是 irc 上面的指令操作罷了
screen 只是方便讓使用者可以利用 server 不關機的優勢,使 irssi 可以連續開著不中斷
然後下次再透過 screen 來接軌回到掛著的 irssi 然後繼續熱血 irc 這樣子
所以,這樣看下面的簡介操作後比較不會搞不懂到底發生啥狀況,如果請教朋友也比較能問到問題處
以下例子皆以 irssi 0.8.10 或以上版本,經實驗都可順利執行
且都以在 FreeNode 上的 OrzLab channel 為例子
(如果不掛 screen 者,這一段請直接跳過)
首先 ssh login 到 server 後
請輸入
screen -RD
-R Reattach if possible, otherwise start a new session.
-D (-r) Detach and logout remote (and reattach here).
irssiirssi/connect irc_server/connect irc.freenode.net/nick you_want_nickname/nick lzy/j #channel_name/j #orzlab/j #channel_name password/wc/disconnect irc_server_name
[Act: 1,2,4,6,9,10]Alt + 1~0 對應 1~10 的 irc channel 編號
Alt + q~p 對應 11~20 的 irc channel 編號
Ctrl + n/p 可切換 上/下 一個 irc channel
然後按鍵盤上的 PageUP/PageDn 可以直接切換 上/下 頁訊息
/recode add #channel_name code_type/recode add #orzlab utf8/recode請直接再下一次/connect irc_server就可以再連接一個新的 irc server ,然後按Alt + 1切換到第一個的特殊頻道上,再按Ctrl + x來切換目前要下達指令的 IRC server名稱。
請下達/who的 irc 指令即可,然後也是一樣按Alt + 1切換到第一個伺服器狀態頻道上觀看
請下達 /whois nickname 的 irc 指令即可,然後也是一樣按 Alt + 1 切換到第一個伺服器狀態頻道上觀看請下達/msg nickname即可開啟一個名為指定暱稱的訊息頻道,一樣用alt + 1~0/q~p來選擇(注意:有些 irc server 會限制此功能,傳訊前請先確認是否有權限)。
為了簡化登入與記憶上的方面,採用 -RD 的參數,所以每次要離開 irssi 時,直接關閉該視窗就好,不需下達任何參數或指令。然後下一次 ssh login 後,只要打 screen -RD 這樣就可以接軌回上次開啟的 irssi 了。首先,先處理 screen 的編碼問題,從 utf8 端要檢視 big5 server 時,先Ctrl + a,然後輸入:encoding big5 utf8,把從 server 將送出的 big5 編碼先轉成 utf8 後再送出,然後輸入"/recode"觀看頻道編碼是否指定正確,照上述設定,理應能順利顯示。
Ctrl + z 或鍵盤上的 Pause 時, irssi 被 suspend 了,如何恢復?請直接輸入 fg 後按 enter ,就可以把剛剛被 suspend 的 irssi 給喚醒。請直接關閉開啟 irssi 的 screen ,請按 Ctrl + k 來關閉 screen window ,然後可以再重新開啟一個全新的 irssi 出來。在需要 auto irc log 的 irc channel 上輸入 /SET autolog ON,即可打開 autolog 功能。直接看例子會比較快,先假設我要讓他自動用 lzy 的暱稱連接到 Freenode 的 irc server 上的 #orzlab/network add -nick lzy Freenode
/server add -auto -network Freenode irc.freenode.net 7000
/channel add -auto #orzlab Freenode
如果是需要 key/password 的 irc channel 的話,則把最後一行改為/channel add -auto #irc_channel_name irc_server_name password
也就是直接把密碼接在後面就可以了
如果需要自動對註冊的暱稱進行認證登入的話(設口令為abcde):/network add -autosendcmd "/^msg nickserv ident abcde;wait 2000" Freenode
在 irssi 裡輸入以下指令,讓 irssi 適時發出聲音訊號:/set beep_when_window_active ON
/set beep_when_away ON
/set beep_msg_level MSGS NOTICES DCC DCCMSGS HILIGHT
/set bell_beeps ON
在 screen 中按下Ctrl +a,Ctrl + g的按鍵,讓 screen 把 irssi 發出來的聲音訊號傳出來
或參考絕地大濕的 blog 一文 <會響的 PuTTY + screen + irssi>
把抓好的 theme (可從官網撈喜歡的),然後複製該 theme 的檔案到 ~/.irssi/ 資料夾路徑,並下達 /SET theme theme_name 來更改該 theme 。因為設定比較繁雜,故只提供官網網址,讓有興趣的朋友可以自己去翻閱。

另外原來系統中的檔案如果是 big5 中文檔名或是檔案中的字元編碼是 big5 ,可以用下列方式轉換成 UTF-8 的格式setenv LC_CTYPE en_US.ISO8859-1
setenv LC_ALL zh_TW.UTF-8
setenv LANG zh_TW.UTF-8
程式使用方法為cd /usr/ports/converters/convmv
make install clean;rehash
檔案內容編碼用 iconv 轉,使用方法為convmv -f big5 -t utf-8 -r –notest [檔名 or 目錄名]
最後是 putty 中的 UTF-8 設定:iconv -f big5 -t utf-8 [檔名] > [檔名]
以上設定完就大功告成。Windows→Translation→charset,改為UTF-8
Windows→Appreance→FontSettings,改成有big5的字體
在Window/Translation中的Received data….. character set選UTF-8。screen
下方的treat CJK ambiguous characters as wide要選。
defc1 off.cshrc,加入下面三行,其它跟LC_*或是LANG有關的通通拿掉
defencoding utf8
bind b encoding big5 utf8 #^A+b會big5轉utf-8
bind u encoding utf8 utf8 #^A+u會變成utf-8
cjkwidth on#[註1]
setenv LANG en_US.UTF-8如果要用telnet上BBS,先按^A+b後再telnet,screen會幫你Big5做轉換。
setenv LC_CTYPE en_US.UTF-8
alias telnet ‘env LANG=zh_TW.Big5 zh-telnet \!*’
ychsiao@FreeBSD [~/tmp] [22:41/W2] convmv -f big5 -t utf-8 -r –notest *irssi
mv “CCNP/CCNP642-831�Ч�.pdf” “CCNP/CCNP642-831教材.pdf”
/recode ADD #XXX Big5FTP Client部分
/recode
/set recode_transliterate ON
/set recode_fallback UTF-8
/set recode_out_default_charset UTF-8
set fileencodings=utf-8,big5,euc-jp,gbk,euc-kr,utf-bom,iso8859-1iconv,檔案編碼轉換
set encoding=utf-8
iconv -f big5 -t utf-8 big5.txt > utf8.txtmutt
set assumed_charset=”big5:gb2312:utf-8″致謝:我的FreeBSD UTF-8部分資訊來自#bsdchat的llwang, chinsan, mhsin, priv。
set ascii_chars=yes
set send_charset=”utf-8:big5:gb2312:us-ascii:iso-8859-1:x-unknown”
me:\
:lang=zh_TW.UTF-8:"file encoding
set fileencodings=utf-8,big5
set fileencoding=utf-8settings = {
core = {
recode_fallback = "UTF-8"; #本端使用utf8
recode_out_default_charset = "UTF-8"; #輸出使用utf8
recode_transliterate = "yes";
real_name = "xxxxx";
user_name = "xxxxx";
nick = "xxxxxx";
};
"fe-common/core" = { term_charset = "UTF-8"; }; #用utf8字元集
"fe-text" = { actlist_sort = "refnum"; };
};cjkwidth off<?php
/* ***** BEGIN LICENSE BLOCK *****
* Version: NPL 1.1/GPL 2.0/LGPL 2.1
*
* Download: http://hsivonen.iki.fi/php-utf8/
*
* The contents of this file are subject to the Netscape Public License
* Version 1.1 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla Communicator client code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1998
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Henri Sivonen, hsivonen@iki.fi
*
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the NPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the NPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
/*
* For the original C++ code, see
* http://lxr.mozilla.org/seamonkey/source/intl/uconv/src/nsUTF8ToUnicode.cpp
* http://lxr.mozilla.org/seamonkey/source/intl/uconv/src/nsUnicodeToUTF8.cpp
*
* The latest version of this file can be obtained from
* http://iki.fi/hsivonen/php-utf8/
*
* Version 1.0, 2003-05-30
*/
/**
* Takes an UTF-8 string and returns an array of ints representing the
* Unicode characters. Astral planes are supported ie. the ints in the
* output can be > 0xFFFF. Occurrances of the BOM are ignored. Surrogates
* are not allowed.
*
* Returns false if the input string isn't a valid UTF-8 octet sequence.
*/
function utf8ToUnicode(&$str)
{
$mState = 0; // cached expected number of octets after the current octet
// until the beginning of the next UTF8 character sequence
$mUcs4 = 0; // cached Unicode character
$mBytes = 1; // cached expected number of octets in the current sequence
$out = array();
$len = strlen($str);
for($i = 0; $i < $len; $i++) {
$in = ord($str{$i});
if (0 == $mState) {
// When mState is zero we expect either a US-ASCII character or a
// multi-octet sequence.
if (0 == (0x80 & ($in))) {
// US-ASCII, pass straight through.
$out[] = $in;
$mBytes = 1;
} else if (0xC0 == (0xE0 & ($in))) {
// First octet of 2 octet sequence
$mUcs4 = ($in);
$mUcs4 = ($mUcs4 & 0x1F) << 6;
$mState = 1;
$mBytes = 2;
} else if (0xE0 == (0xF0 & ($in))) {
// First octet of 3 octet sequence
$mUcs4 = ($in);
$mUcs4 = ($mUcs4 & 0x0F) << 12;
$mState = 2;
$mBytes = 3;
} else if (0xF0 == (0xF8 & ($in))) {
// First octet of 4 octet sequence
$mUcs4 = ($in);
$mUcs4 = ($mUcs4 & 0x07) << 18;
$mState = 3;
$mBytes = 4;
} else if (0xF8 == (0xFC & ($in))) {
/* First octet of 5 octet sequence.
*
* This is illegal because the encoded codepoint must be either
* (a) not the shortest form or
* (b) outside the Unicode range of 0-0x10FFFF.
* Rather than trying to resynchronize, we will carry on until the end
* of the sequence and let the later error handling code catch it.
*/
$mUcs4 = ($in);
$mUcs4 = ($mUcs4 & 0x03) << 24;
$mState = 4;
$mBytes = 5;
} else if (0xFC == (0xFE & ($in))) {
// First octet of 6 octet sequence, see comments for 5 octet sequence.
$mUcs4 = ($in);
$mUcs4 = ($mUcs4 & 1) << 30;
$mState = 5;
$mBytes = 6;
} else {
/* Current octet is neither in the US-ASCII range nor a legal first
* octet of a multi-octet sequence.
*/
return false;
}
} else {
// When mState is non-zero, we expect a continuation of the multi-octet
// sequence
if (0x80 == (0xC0 & ($in))) {
// Legal continuation.
$shift = ($mState - 1) * 6;
$tmp = $in;
$tmp = ($tmp & 0x0000003F) << $shift;
$mUcs4 |= $tmp;
if (0 == --$mState) {
/* End of the multi-octet sequence. mUcs4 now contains the final
* Unicode codepoint to be output
*
* Check for illegal sequences and codepoints.
*/
// From Unicode 3.1, non-shortest form is illegal
if (((2 == $mBytes) && ($mUcs4 < 0x0080)) ||
((3 == $mBytes) && ($mUcs4 < 0x0800)) ||
((4 == $mBytes) && ($mUcs4 < 0x10000)) ||
(4 < $mBytes) ||
// From Unicode 3.2, surrogate characters are illegal
(($mUcs4 & 0xFFFFF800) == 0xD800) ||
// Codepoints outside the Unicode range are illegal
($mUcs4 > 0x10FFFF)) {
return false;
}
if (0xFEFF != $mUcs4) {
// BOM is legal but we don't want to output it
$out[] = $mUcs4;
}
//initialize UTF8 cache
$mState = 0;
$mUcs4 = 0;
$mBytes = 1;
}
} else {
/* ((0xC0 & (*in) != 0x80) && (mState != 0))
*
* Incomplete multi-octet sequence.
*/
return false;
}
}
}
return $out;
}
/**
* Takes an array of ints representing the Unicode characters and returns
* a UTF-8 string. Astral planes are supported ie. the ints in the
* input can be > 0xFFFF. Occurrances of the BOM are ignored. Surrogates
* are not allowed.
*
* Returns false if the input array contains ints that represent
* surrogates or are outside the Unicode range.
*/
function unicodeToUtf8(&$arr)
{
$dest = '';
foreach ($arr as $src) {
if($src < 0) {
return false;
} else if ( $src <= 0x007f) {
$dest .= chr($src);
} else if ($src <= 0x07ff) {
$dest .= chr(0xc0 | ($src >> 6));
$dest .= chr(0x80 | ($src & 0x003f));
} else if($src == 0xFEFF) {
// nop -- zap the BOM
} else if ($src >= 0xD800 && $src <= 0xDFFF) {
// found a surrogate
return false;
} else if ($src <= 0xffff) {
$dest .= chr(0xe0 | ($src >> 12));
$dest .= chr(0x80 | (($src >> 6) & 0x003f));
$dest .= chr(0x80 | ($src & 0x003f));
} else if ($src <= 0x10ffff) {
$dest .= chr(0xf0 | ($src >> 18));
$dest .= chr(0x80 | (($src >> 12) & 0x3f));
$dest .= chr(0x80 | (($src >> 6) & 0x3f));
$dest .= chr(0x80 | ($src & 0x3f));
} else {
// out of range
return false;
}
}
return $dest;
}
?><?php
function uniord($c) {
$h = ord($c{0});
if ($h <= 0x7F) {
return $h;
} else if ($h < 0xC2) {
return false;
} else if ($h <= 0xDF) {
return ($h & 0x1F) << 6 | (ord($c{1}) & 0x3F);
} else if ($h <= 0xEF) {
return ($h & 0x0F) << 12 | (ord($c{1}) & 0x3F) << 6
| (ord($c{2}) & 0x3F);
} else if ($h <= 0xF4) {
return ($h & 0x0F) << 18 | (ord($c{1}) & 0x3F) << 12
| (ord($c{2}) & 0x3F) << 6
| (ord($c{3}) & 0x3F);
} else {
return false;
}
}
?>
<?php
//Non-English Character Matching:
//The "character set" block (square brackets) allow us to match characters, but since we can only range english chars, one trick is to use ASCII or UNICODE matching like this:
//ASCII matching can be performed like this:
preg_match('/[\x00-\x80]+/', $str);
//Unicode matching can be performed like this:
preg_match('/[^\u0000-\u0080]+/', $str);
//To our case, to match only non-english chars use:
preg_match('/[^\x00-\x80]+/', $str);
//To match ALL chars (both english & non english & some non-chars as well, perhaps) use:
preg_match('/[a-zA-Z\x00-\xFF]+/', $str);
// Chinese characters range in unicode (verify?)
preg_match('/^[u4e00-u9fa5],{0,}$/', $str);
?>
<?php
//mb_internal_encoding("UTF-8");
$conn = mssql_connect( "MyServer2k", "user", "password" );
mssql_select_db('testing', $conn);
$query = "select top 10 * from member2";
$result = mssql_query( $query );
while( $row = mssql_fetch_array( $result ) ) {
//echo strtoupper(ucs2toutf8($row['title']))."<br>";
//echo iconv('UCS-2LE', 'UTF-8', $row['title'])."<br>";
$title = $row['note2'];
//$whichcode = mb_detect_encoding( $row['title'], "auto" );
//$whichcode = is_utf8( $row['title'] );
//$title = mb_convert_encoding( $row['title'], "UTF-8", "UCS-2LE" );
//$title = preg_replace("/([\xE0-\xFA])/e","chr(215).chr(ord(\${1})-80)",$title);
//$title = iconv( "", "UTF-8", $title );
//$title = ucs2html( $title );
echo $title."<br>";
}
echo "code: ".$whichcode;
function is_utf8($string) {
// From http://w3.org/International/questions/qa-forms-utf-8.html
return preg_match('%^(?:
[\x09\x0A\x0D\x20-\x7E] # ASCII
| [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte
| \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs
| [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
| \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates
| \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
| [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15
| \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
)*$%xs', $string);
} // function is_utf8
function ucs2toutf8($str)
{
for ($i=0;$i < strlen($str);$i+=4)
{
$substring1 = $str[$i].$str[$i+1];
$substring2 = $str[$i+2].$str[$i+3];
if ($substring1 == "00")
{
$byte1 = "";
$byte2 = $substring2;
}
else
{
$substring = $substring1.$substring2;
$byte1 = dechex(192+(hexdec($substring)/64));
$byte2 = dechex(128+(hexdec($substring)%64));
}
$utf8 .= $byte1.$byte2;
}
return $utf8;
}
function CP1251toUTF8($string){
$out = '';
for ($i = 0; $i < strlen($string); ++$i){
$ch = ord($string{$i});
if ($ch < 0x80) $out .= chr($ch);
else
if ($ch >= 0xC0)
if ($ch < 0xF0)
$out .= "\xD0".chr(0x90 + $ch - 0xC0); // А-Я, а-п (A-YA, a-p)
else $out .= "\xD1".chr(0x80 + $ch - 0xF0); // р-я (r-ya)
else
switch($ch){
case 0xA8: $out .= "\xD0\x81"; break; // YO
case 0xB8: $out .= "\xD1\x91"; break; // yo
// ukrainian
case 0xA1: $out .= "\xD0\x8E"; break; // Ў (U)
case 0xA2: $out .= "\xD1\x9E"; break; // ў (u)
case 0xAA: $out .= "\xD0\x84"; break; // Є (e)
case 0xAF: $out .= "\xD0\x87"; break; // Ї (I..)
case 0xB2: $out .= "\xD0\x86"; break; // I (I)
case 0xB3: $out .= "\xD1\x96"; break; // i (i)
case 0xBA: $out .= "\xD1\x94"; break; // є (e)
case 0xBF: $out .= "\xD1\x97"; break; // ї (i..)
// chuvashian
case 0x8C: $out .= "\xD3\x90"; break; // Ӑ (A)
case 0x8D: $out .= "\xD3\x96"; break; // Ӗ (E)
case 0x8E: $out .= "\xD2\xAA"; break; // Ҫ (SCH)
case 0x8F: $out .= "\xD3\xB2"; break; // Ӳ (U)
case 0x9C: $out .= "\xD3\x91"; break; // ӑ (a)
case 0x9D: $out .= "\xD3\x97"; break; // ӗ (e)
case 0x9E: $out .= "\xD2\xAB"; break; // ҫ (sch)
case 0x9F: $out .= "\xD3\xB3"; break; // ӳ (u)
}
}
return $out;
}
function ucs2html($str) {
$str=trim($str); // if you are reading from file
$len=strlen($str);
$html='';
for($i=0;$i < $len;$i+=2)
$html.=''.hexdec(dechex(ord($str[$i+1])).
sprintf("%02s",dechex(ord($str[$i])))).';';
return($html);
}
?>
<?php
### str to image.
// Path to our font file
$font = 'mingliu.ttc';
$size = 10;
$width = 465;
$width_padding = 15;
$text = "How To Become A Hacker Why This Document? As editor of the Jargon File, I often get email requests from enthusiastic network newbies asking (in effect) \"how can I learn to be a wizard hacker?\". Oddly enough there don't seem to be any FAQs or Web documents that address this vital question, so here's mine. 身為 Jargon File 的編輯, 常有一些網路新手發 mail 問我 \"如何成為一個厲害的 hacker?\". 但, 很奇怪的, 似乎沒有任何的 FAQs 或 Web documents 說明這麼重要 的問題, 所以我寫了一份我自己的看法. If you are reading a snapshot of this document offline, the current version lives at href=\"http://www.ccil.org/~esr/faqs/hacker-howto.html. 如果你是以 offline 的方式在看這一份文件的某一個版本, 那麼你可以在 \"http://www.ccil.org/~esr/faqs/hacker-howto.html\" 找到這份文件的目前最新版本. What Is A Hacker? 怎麼樣才算是一位 Hacker ?? The Jargon File contains a bunch of definitions of the term 'hacker', most having to do with technical adeptness and a delight in solving problems and overcoming limits. If you want to know how to become a hacker, though, only two are really relevant. 在 Jargon File 裏有一堆關於 'hacker' 這個名詞的定義, 大部份必須是技術上的 行家或熱衷於解決問題, 克服限制的人. 然而, 如果你想知道如何成為一位 hacker, 有兩件事是很有關連的.";
$textArr = _mb_wordwrap($text, $font, $size, $width);
$heightTmp = count($textArr) * 20;
$height = $heightTmp + 50;
$text = '';
foreach ($textArr as $line) {
$text .= $line . "\n";
}
// Create a 300x150 image
$im = imagecreatetruecolor($width + $width_padding, $height);
$black = imagecolorallocate($im, 0, 0, 0);
$white = imagecolorallocate($im, 255, 255, 255);
$red = imagecolorallocate($im, 255, 0, 0);
$green = imagecolorallocate($im, 0, 128, 0);
// Set the background to be white
imagefilledrectangle($im, 0, 0, $width + 20, $height, $white);
$x = 10;
$y = 20;
$angle = 0; // ### The angle in degrees, with 0 degrees being left-to-right reading text. Higher values represent a counter-clockwise rotation. For example, a value of 90 would result in bottom-to-top reading text.
// Write it
imagettftext($im, $size, $angle, $x, $y, $black, $font, $text);
$textTmp = "Copyright © 2009 www.randomdomain.com\n";
$textTmp .= "All right reserved. 版權所有,未經同意,不得翻印";
imagettftext($im, $size, $angle, $x, $y + $heightTmp, $green, $font, $textTmp);
// Set the content-type
// if you want to output to browser, uncomment following line, and remove the file name from next line.
header('Content-type: image/png');
// Using imagepng() results in clearer text compared with imagejpeg()
imagepng($im);
imagedestroy($im);
/**
* Mickey9801 at ComicParty dot com:
* Most of functions shared here seems only work with western language and
* is not suitable for multibyte characters (like Chinese). I have written
* a function using mb_string functions to match the need of multibyte character
* word wrapping.
* I also added some machanism so that English word won't be cut off at the
* end of line. Of couse you must use unicode string on GD.
* @param
* @return
*/
function _mb_wordwrap($txt,$font,$size,$width, $encoding = 'UTF-8') {
$pointer = 0;
$this_line_start = 0;
$this_line_strlen = 1;
$single_byte_stack = "";
$result_lines = array();
$txtLen = mb_strlen($txt, 'UTF-8');
while ($pointer <= $txtLen) {
$this_char = mb_substr($txt, $pointer, 1, $encoding);
$tmp_line = mb_substr($txt, $this_line_start, $this_line_strlen, $encoding);
$tmp_line_bbox = imagettfbbox($size,0 ,$font ,$tmp_line);
$this_line_width = $tmp_line_bbox[2]-$tmp_line_bbox[0];
if ($this_line_width > $width) {
// If last word is alphanumeric, put it to next line rather then cut it off
if ($single_byte_stack != "") {
$stack_len = mb_strlen($single_byte_stack, $encoding);
$this_line_strlen -= $stack_len;
$pointer -= $stack_len;
}
$result_lines[] = mb_substr($txt, $this_line_start, $this_line_strlen-1, $encoding);
$this_line_start = $pointer;
$this_line_strlen = 1;
$single_byte_stack = "";
} else {
// Prevent to cut off english word at the end of line
// if this character is a alphanumeric character or open bracket, put it into stack
if (
(ord($this_char)>=48 && ord($this_char)<=57) ||
(ord($this_char)>=65 && ord($this_char)<=91) ||
(ord($this_char)>=97 && ord($this_char)<=123) ||
ord($this_char)==40 ||
ord($this_char)==60 ||
($single_byte_stack=="" && (ord($this_char)==34 || ord($this_char)==39))
) $single_byte_stack .= $this_char;
else $single_byte_stack = ""; // Clear stack if met multibyte character and not line end
$this_line_strlen++;
$pointer++;
}
}
// Move remained word to result
$result_lines[] = mb_substr($txt, $this_line_start, $txtLen, $encoding);
return $result_lines;
}
?>
$strEncode = mb_detect_encoding($contents, "UTF-8, ISO-8859-1");
if ($strEncode == 'ISO-8859-1') {
$contents = mb_convert_encoding($contents, 'UTF-8', 'CP1252');
}
$contents = mysql_real_escape_string($contents);
<?php
$target = 'some text';
if(preg_match('/
e # Comments here
/x',$target)) {
print "Target 1 hit.\n";
}
if(preg_match('/
e # /Comments here with slash
/x',$target)) {
print "Target 1 hit.\n";
}
?><?php
$examples = array(
'Valid ASCII' => "a",
'Valid 2 Octet Sequence' => "\xc3\xb1",
'Invalid 2 Octet Sequence' => "\xc3\x28",
'Invalid Sequence Identifier' => "\xa0\xa1",
'Valid 3 Octet Sequence' => "\xe2\x82\xa1",
'Invalid 3 Octet Sequence (in 2nd Octet)' => "\xe2\x28\xa1",
'Invalid 3 Octet Sequence (in 3rd Octet)' => "\xe2\x82\x28",
'Valid 4 Octet Sequence' => "\xf0\x90\x8c\xbc",
'Invalid 4 Octet Sequence (in 2nd Octet)' => "\xf0\x28\x8c\xbc",
'Invalid 4 Octet Sequence (in 3rd Octet)' => "\xf0\x90\x28\xbc",
'Invalid 4 Octet Sequence (in 4th Octet)' => "\xf0\x28\x8c\x28",
'Valid 5 Octet Sequence (but not Unicode!)' => "\xf8\xa1\xa1\xa1\xa1",
'Valid 6 Octet Sequence (but not Unicode!)' => "\xfc\xa1\xa1\xa1\xa1\xa1",
);
echo "++Invalid UTF-8 in pattern\n";
foreach ( $examples as $name => $str ) {
echo "$name\n";
preg_match("/".$str."/u",'Testing');
}
echo "++ preg_match() examples\n";
foreach ( $examples as $name => $str ) {
preg_match("/\xf8\xa1\xa1\xa1\xa1/u", $str, $ar);
echo "$name: ";
if ( count($ar) == 0 ) {
echo "Matched nothing!\n";
} else {
echo "Matched {$ar[0]}\n";
}
}
echo "++ preg_match_all() examples\n";
foreach ( $examples as $name => $str ) {
preg_match_all('/./u', $str, $ar);
echo "$name: ";
$num_utf8_chars = count($ar[0]);
if ( $num_utf8_chars == 0 ) {
echo "Matched nothing!\n";
} else {
echo "Matched $num_utf8_chars character\n";
}
}
?>csaba at alum dot mit dot edu<?php $lineFirst = "This is a new first line<br>\r\n"; $lineLast = "This is a new last line<br>\r\n"; $page = <<<EOD <html><head> <title>This is a test page</title> </head><body> This is the first line<br> Hi Fred<br> Hi Bill<br> This is the last line<br> </body> </html> EOD; $re = "/<body>.*^(.+)(^.*?^)(.+)(^<\\/body>.*?)/smU"; if (preg_match($re, $page, $aMatch, PREG_OFFSET_CAPTURE)) $newPage = substr($text, 0, $aMatch[1][1]) . $lineFirst . $aMatch[2][0] . $lineLast . $aMatch[4][0]; print $newPage; ?>
<?php
function drupal_validate_utf8($text) {
if (strlen($text) == 0) {
return TRUE;
}
return (preg_match('/^./us', $text) == 1);
}
?>