<?php
/*--------------------------------------------------------- 
 * File:string.php
 * Author:Tomix
 * Description: 
 * Created:2009
 * -------------------------------------------------------
 * Modified history:2023/08/22
 * Copyright © 2023 蘋果世界股份有限公司 版權所有
 * -------------------------------------------------------
 */
class string_iweb {
	// 計算utf-8字符串長度
	public static function strlen(string $str): int {
		return mb_strlen($str, "utf-8");
	}
	
	// 返回utf-8子字符串
	public static function substr(string $str, int $start = 0, int $length = -1): string {
		if ($length < 0) $length = self::strlen($str);
		return mb_substr($str, $start, $length);
	}
	
	// 字符串是空或null
	public static function isEmptyOrNull($str): bool {
		return empty($str);
	}

	public static function cut_str($msg, $cut_size, $charset = "UTF-8", $suffix = "...") {
		if ($cut_size <= 0) return $msg;

		$i = 1;
		$han = 0;
		$eng = 0;
		$str = "";

		while ($i <= strlen($msg)) {
			if (ord($msg[($i - 1)]) > 127) {
				$han++;
				if ($charset == "UTF-8") {
					$str .= $msg[($i - 1)] . $msg[($i)] . $msg[($i + 1)];
					$i = $i + 3;
				} else {
					$str .= $msg[($i - 1)] . $msg[($i)];
					$i = $i + 2;
				}
			} else {
				$eng++;
				$str .= $msg[($i - 1)];
				$i++;
			}

			if (($han + $eng) == $cut_size) break;
		}

		$suffix = ($han + $eng) < $cut_size ? "" : $suffix;
		return $str . $suffix;
	}
}
?>