100分求個 檢測字串長度
$str[0] = "123asd你好[哈哈]"
$str[1] = "123asd你好[你好不好啊]"
//一個中文一個字元(utf-8的編碼) 符號 [這裡面的字和外邊的符號算一個字元]
然後計算長度
結果是$str[0]和$str[1]為長度9
最好寫成一個函數。謝謝了
------解決方案--------------------
我沒太看懂樓主的題,不過函數,手頭上有一個。
PHP code
/** * 得到utf8 的長度 * @author mu_rain * @param String $str * @return Int */ static function strlen_utf8($str) { $i = 0; $count = 0; $len = strlen ($str); while ($i < $len) { $chr = ord ($str[$i]); $count++; $i++; if($i >= $len) break; if($chr & 0x80) { $chr <<= 1; while ($chr & 0x80) { $i++; $chr <<= 1; } } } return $count; }
------解決方案--------------------
PHP code
function myLen($str,$startTag='[',$endTag=']',$encoding='utf-8') { $st = preg_quote($startTag); $et = preg_quote($endTag); return mb_strlen(preg_replace("#{$st}[^{$et}]*{$et}#","~",$str),$encoding); }echo myLen("123asd你好[哈哈]");//9
------解決方案--------------------
附贈字串函數一堆 ,慢用。
PHP code