Mbstring.php 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Polyfill\Mbstring;
  11. /**
  12. * Partial mbstring implementation in PHP, iconv based, UTF-8 centric.
  13. *
  14. * Implemented:
  15. * - mb_chr - Returns a specific character from its Unicode code point
  16. * - mb_convert_encoding - Convert character encoding
  17. * - mb_convert_variables - Convert character code in variable(s)
  18. * - mb_decode_mimeheader - Decode string in MIME header field
  19. * - mb_encode_mimeheader - Encode string for MIME header XXX NATIVE IMPLEMENTATION IS REALLY BUGGED
  20. * - mb_decode_numericentity - Decode HTML numeric string reference to character
  21. * - mb_encode_numericentity - Encode character to HTML numeric string reference
  22. * - mb_convert_case - Perform case folding on a string
  23. * - mb_detect_encoding - Detect character encoding
  24. * - mb_get_info - Get internal settings of mbstring
  25. * - mb_http_input - Detect HTTP input character encoding
  26. * - mb_http_output - Set/Get HTTP output character encoding
  27. * - mb_internal_encoding - Set/Get internal character encoding
  28. * - mb_list_encodings - Returns an array of all supported encodings
  29. * - mb_ord - Returns the Unicode code point of a character
  30. * - mb_output_handler - Callback function converts character encoding in output buffer
  31. * - mb_scrub - Replaces ill-formed byte sequences with substitute characters
  32. * - mb_strlen - Get string length
  33. * - mb_strpos - Find position of first occurrence of string in a string
  34. * - mb_strrpos - Find position of last occurrence of a string in a string
  35. * - mb_str_split - Convert a string to an array
  36. * - mb_strtolower - Make a string lowercase
  37. * - mb_strtoupper - Make a string uppercase
  38. * - mb_substitute_character - Set/Get substitution character
  39. * - mb_substr - Get part of string
  40. * - mb_stripos - Finds position of first occurrence of a string within another, case insensitive
  41. * - mb_stristr - Finds first occurrence of a string within another, case insensitive
  42. * - mb_strrchr - Finds the last occurrence of a character in a string within another
  43. * - mb_strrichr - Finds the last occurrence of a character in a string within another, case insensitive
  44. * - mb_strripos - Finds position of last occurrence of a string within another, case insensitive
  45. * - mb_strstr - Finds first occurrence of a string within another
  46. * - mb_strwidth - Return width of string
  47. * - mb_substr_count - Count the number of substring occurrences
  48. * - mb_ucfirst - Make a string's first character uppercase
  49. * - mb_lcfirst - Make a string's first character lowercase
  50. * - mb_trim - Strip whitespace (or other characters) from the beginning and end of a string
  51. * - mb_ltrim - Strip whitespace (or other characters) from the beginning of a string
  52. * - mb_rtrim - Strip whitespace (or other characters) from the end of a string
  53. *
  54. * Not implemented:
  55. * - mb_convert_kana - Convert "kana" one from another ("zen-kaku", "han-kaku" and more)
  56. * - mb_ereg_* - Regular expression with multibyte support
  57. * - mb_parse_str - Parse GET/POST/COOKIE data and set global variable
  58. * - mb_preferred_mime_name - Get MIME charset string
  59. * - mb_regex_encoding - Returns current encoding for multibyte regex as string
  60. * - mb_regex_set_options - Set/Get the default options for mbregex functions
  61. * - mb_send_mail - Send encoded mail
  62. * - mb_split - Split multibyte string using regular expression
  63. * - mb_strcut - Get part of string
  64. * - mb_strimwidth - Get truncated string with specified width
  65. *
  66. * @author Nicolas Grekas <p@tchwork.com>
  67. *
  68. * @internal
  69. */
  70. final class Mbstring
  71. {
  72. public const MB_CASE_FOLD = \PHP_INT_MAX;
  73. private const SIMPLE_CASE_FOLD = [
  74. ['µ', 'ſ', "\xCD\x85", 'ς', "\xCF\x90", "\xCF\x91", "\xCF\x95", "\xCF\x96", "\xCF\xB0", "\xCF\xB1", "\xCF\xB5", "\xE1\xBA\x9B", "\xE1\xBE\xBE"],
  75. ['μ', 's', 'ι', 'σ', 'β', 'θ', 'φ', 'π', 'κ', 'ρ', 'ε', "\xE1\xB9\xA1", 'ι'],
  76. ];
  77. private static $encodingList = ['ASCII', 'UTF-8'];
  78. private static $language = 'neutral';
  79. private static $internalEncoding = 'UTF-8';
  80. public static function mb_convert_encoding($s, $toEncoding, $fromEncoding = null)
  81. {
  82. if (\is_array($s)) {
  83. $r = [];
  84. foreach ($s as $str) {
  85. $r[] = self::mb_convert_encoding($str, $toEncoding, $fromEncoding);
  86. }
  87. return $r;
  88. }
  89. if (\is_array($fromEncoding) || (null !== $fromEncoding && false !== strpos($fromEncoding, ','))) {
  90. $fromEncoding = self::mb_detect_encoding($s, $fromEncoding);
  91. } else {
  92. $fromEncoding = self::getEncoding($fromEncoding);
  93. }
  94. $toEncoding = self::getEncoding($toEncoding);
  95. if ('BASE64' === $fromEncoding) {
  96. $s = base64_decode($s);
  97. $fromEncoding = $toEncoding;
  98. }
  99. if ('BASE64' === $toEncoding) {
  100. return base64_encode($s);
  101. }
  102. if ('HTML-ENTITIES' === $toEncoding || 'HTML' === $toEncoding) {
  103. if ('HTML-ENTITIES' === $fromEncoding || 'HTML' === $fromEncoding) {
  104. $fromEncoding = 'Windows-1252';
  105. }
  106. if ('UTF-8' !== $fromEncoding) {
  107. $s = iconv($fromEncoding, 'UTF-8//IGNORE', $s);
  108. }
  109. return preg_replace_callback('/[\x80-\xFF]+/', [__CLASS__, 'html_encoding_callback'], $s);
  110. }
  111. if ('HTML-ENTITIES' === $fromEncoding) {
  112. $s = html_entity_decode($s, \ENT_COMPAT, 'UTF-8');
  113. $fromEncoding = 'UTF-8';
  114. }
  115. return iconv($fromEncoding, $toEncoding.'//IGNORE', $s);
  116. }
  117. public static function mb_convert_variables($toEncoding, $fromEncoding, &...$vars)
  118. {
  119. $ok = true;
  120. array_walk_recursive($vars, function (&$v) use (&$ok, $toEncoding, $fromEncoding) {
  121. if (false === $v = self::mb_convert_encoding($v, $toEncoding, $fromEncoding)) {
  122. $ok = false;
  123. }
  124. });
  125. return $ok ? $fromEncoding : false;
  126. }
  127. public static function mb_decode_mimeheader($s)
  128. {
  129. return iconv_mime_decode($s, 2, self::$internalEncoding);
  130. }
  131. public static function mb_encode_mimeheader($s, $charset = null, $transferEncoding = null, $linefeed = null, $indent = null)
  132. {
  133. trigger_error('mb_encode_mimeheader() is bugged. Please use iconv_mime_encode() instead', \E_USER_WARNING);
  134. }
  135. public static function mb_decode_numericentity($s, $convmap, $encoding = null)
  136. {
  137. if (null !== $s && !\is_scalar($s) && !(\is_object($s) && method_exists($s, '__toString'))) {
  138. trigger_error('mb_decode_numericentity() expects parameter 1 to be string, '.\gettype($s).' given', \E_USER_WARNING);
  139. return null;
  140. }
  141. if (!\is_array($convmap) || (80000 > \PHP_VERSION_ID && !$convmap)) {
  142. return false;
  143. }
  144. if (null !== $encoding && !\is_scalar($encoding)) {
  145. trigger_error('mb_decode_numericentity() expects parameter 3 to be string, '.\gettype($s).' given', \E_USER_WARNING);
  146. return ''; // Instead of null (cf. mb_encode_numericentity).
  147. }
  148. $s = (string) $s;
  149. if ('' === $s) {
  150. return '';
  151. }
  152. $encoding = self::getEncoding($encoding);
  153. if ('UTF-8' === $encoding) {
  154. $encoding = null;
  155. if (!preg_match('//u', $s)) {
  156. $s = @iconv('UTF-8', 'UTF-8//IGNORE', $s);
  157. }
  158. } else {
  159. $s = iconv($encoding, 'UTF-8//IGNORE', $s);
  160. }
  161. $cnt = floor(\count($convmap) / 4) * 4;
  162. for ($i = 0; $i < $cnt; $i += 4) {
  163. // collector_decode_htmlnumericentity ignores $convmap[$i + 3]
  164. $convmap[$i] += $convmap[$i + 2];
  165. $convmap[$i + 1] += $convmap[$i + 2];
  166. }
  167. $s = preg_replace_callback('/&#(?:0*([0-9]+)|x0*([0-9a-fA-F]+))(?!&);?/', function (array $m) use ($cnt, $convmap) {
  168. $c = isset($m[2]) ? (int) hexdec($m[2]) : $m[1];
  169. for ($i = 0; $i < $cnt; $i += 4) {
  170. if ($c >= $convmap[$i] && $c <= $convmap[$i + 1]) {
  171. return self::mb_chr($c - $convmap[$i + 2]);
  172. }
  173. }
  174. return $m[0];
  175. }, $s);
  176. if (null === $encoding) {
  177. return $s;
  178. }
  179. return iconv('UTF-8', $encoding.'//IGNORE', $s);
  180. }
  181. public static function mb_encode_numericentity($s, $convmap, $encoding = null, $is_hex = false)
  182. {
  183. if (null !== $s && !\is_scalar($s) && !(\is_object($s) && method_exists($s, '__toString'))) {
  184. trigger_error('mb_encode_numericentity() expects parameter 1 to be string, '.\gettype($s).' given', \E_USER_WARNING);
  185. return null;
  186. }
  187. if (!\is_array($convmap) || (80000 > \PHP_VERSION_ID && !$convmap)) {
  188. return false;
  189. }
  190. if (null !== $encoding && !\is_scalar($encoding)) {
  191. trigger_error('mb_encode_numericentity() expects parameter 3 to be string, '.\gettype($s).' given', \E_USER_WARNING);
  192. return null; // Instead of '' (cf. mb_decode_numericentity).
  193. }
  194. if (null !== $is_hex && !\is_scalar($is_hex)) {
  195. trigger_error('mb_encode_numericentity() expects parameter 4 to be boolean, '.\gettype($s).' given', \E_USER_WARNING);
  196. return null;
  197. }
  198. $s = (string) $s;
  199. if ('' === $s) {
  200. return '';
  201. }
  202. $encoding = self::getEncoding($encoding);
  203. if ('UTF-8' === $encoding) {
  204. $encoding = null;
  205. if (!preg_match('//u', $s)) {
  206. $s = @iconv('UTF-8', 'UTF-8//IGNORE', $s);
  207. }
  208. } else {
  209. $s = iconv($encoding, 'UTF-8//IGNORE', $s);
  210. }
  211. static $ulenMask = ["\xC0" => 2, "\xD0" => 2, "\xE0" => 3, "\xF0" => 4];
  212. $cnt = floor(\count($convmap) / 4) * 4;
  213. $i = 0;
  214. $len = \strlen($s);
  215. $result = '';
  216. while ($i < $len) {
  217. $ulen = $s[$i] < "\x80" ? 1 : $ulenMask[$s[$i] & "\xF0"];
  218. $uchr = substr($s, $i, $ulen);
  219. $i += $ulen;
  220. $c = self::mb_ord($uchr);
  221. for ($j = 0; $j < $cnt; $j += 4) {
  222. if ($c >= $convmap[$j] && $c <= $convmap[$j + 1]) {
  223. $cOffset = ($c + $convmap[$j + 2]) & $convmap[$j + 3];
  224. $result .= $is_hex ? sprintf('&#x%X;', $cOffset) : '&#'.$cOffset.';';
  225. continue 2;
  226. }
  227. }
  228. $result .= $uchr;
  229. }
  230. if (null === $encoding) {
  231. return $result;
  232. }
  233. return iconv('UTF-8', $encoding.'//IGNORE', $result);
  234. }
  235. public static function mb_convert_case($s, $mode, $encoding = null)
  236. {
  237. $s = (string) $s;
  238. if ('' === $s) {
  239. return '';
  240. }
  241. $encoding = self::getEncoding($encoding);
  242. if ('UTF-8' === $encoding) {
  243. $encoding = null;
  244. if (!preg_match('//u', $s)) {
  245. $s = @iconv('UTF-8', 'UTF-8//IGNORE', $s);
  246. }
  247. } else {
  248. $s = iconv($encoding, 'UTF-8//IGNORE', $s);
  249. }
  250. if (\MB_CASE_TITLE == $mode) {
  251. static $titleRegexp = null;
  252. if (null === $titleRegexp) {
  253. $titleRegexp = self::getData('titleCaseRegexp');
  254. }
  255. $s = preg_replace_callback($titleRegexp, [__CLASS__, 'title_case'], $s);
  256. } else {
  257. if (\MB_CASE_UPPER == $mode) {
  258. static $upper = null;
  259. if (null === $upper) {
  260. $upper = self::getData('upperCase');
  261. }
  262. $map = $upper;
  263. } else {
  264. if (self::MB_CASE_FOLD === $mode) {
  265. static $caseFolding = null;
  266. if (null === $caseFolding) {
  267. $caseFolding = self::getData('caseFolding');
  268. }
  269. $s = strtr($s, $caseFolding);
  270. }
  271. static $lower = null;
  272. if (null === $lower) {
  273. $lower = self::getData('lowerCase');
  274. }
  275. $map = $lower;
  276. }
  277. static $ulenMask = ["\xC0" => 2, "\xD0" => 2, "\xE0" => 3, "\xF0" => 4];
  278. $i = 0;
  279. $len = \strlen($s);
  280. while ($i < $len) {
  281. $ulen = $s[$i] < "\x80" ? 1 : $ulenMask[$s[$i] & "\xF0"];
  282. $uchr = substr($s, $i, $ulen);
  283. $i += $ulen;
  284. if (isset($map[$uchr])) {
  285. $uchr = $map[$uchr];
  286. $nlen = \strlen($uchr);
  287. if ($nlen == $ulen) {
  288. $nlen = $i;
  289. do {
  290. $s[--$nlen] = $uchr[--$ulen];
  291. } while ($ulen);
  292. } else {
  293. $s = substr_replace($s, $uchr, $i - $ulen, $ulen);
  294. $len += $nlen - $ulen;
  295. $i += $nlen - $ulen;
  296. }
  297. }
  298. }
  299. }
  300. if (null === $encoding) {
  301. return $s;
  302. }
  303. return iconv('UTF-8', $encoding.'//IGNORE', $s);
  304. }
  305. public static function mb_internal_encoding($encoding = null)
  306. {
  307. if (null === $encoding) {
  308. return self::$internalEncoding;
  309. }
  310. $normalizedEncoding = self::getEncoding($encoding);
  311. if ('UTF-8' === $normalizedEncoding || false !== @iconv($normalizedEncoding, $normalizedEncoding, ' ')) {
  312. self::$internalEncoding = $normalizedEncoding;
  313. return true;
  314. }
  315. if (80000 > \PHP_VERSION_ID) {
  316. return false;
  317. }
  318. throw new \ValueError(sprintf('Argument #1 ($encoding) must be a valid encoding, "%s" given', $encoding));
  319. }
  320. public static function mb_language($lang = null)
  321. {
  322. if (null === $lang) {
  323. return self::$language;
  324. }
  325. switch ($normalizedLang = strtolower($lang)) {
  326. case 'uni':
  327. case 'neutral':
  328. self::$language = $normalizedLang;
  329. return true;
  330. }
  331. if (80000 > \PHP_VERSION_ID) {
  332. return false;
  333. }
  334. throw new \ValueError(sprintf('Argument #1 ($language) must be a valid language, "%s" given', $lang));
  335. }
  336. public static function mb_list_encodings()
  337. {
  338. return ['UTF-8'];
  339. }
  340. public static function mb_encoding_aliases($encoding)
  341. {
  342. switch (strtoupper($encoding)) {
  343. case 'UTF8':
  344. case 'UTF-8':
  345. return ['utf8'];
  346. }
  347. return false;
  348. }
  349. public static function mb_check_encoding($var = null, $encoding = null)
  350. {
  351. if (null === $encoding) {
  352. if (null === $var) {
  353. return false;
  354. }
  355. $encoding = self::$internalEncoding;
  356. }
  357. if (!\is_array($var)) {
  358. return self::mb_detect_encoding($var, [$encoding]) || false !== @iconv($encoding, $encoding, $var);
  359. }
  360. foreach ($var as $key => $value) {
  361. if (!self::mb_check_encoding($key, $encoding)) {
  362. return false;
  363. }
  364. if (!self::mb_check_encoding($value, $encoding)) {
  365. return false;
  366. }
  367. }
  368. return true;
  369. }
  370. public static function mb_detect_encoding($str, $encodingList = null, $strict = false)
  371. {
  372. if (null === $encodingList) {
  373. $encodingList = self::$encodingList;
  374. } else {
  375. if (!\is_array($encodingList)) {
  376. $encodingList = array_map('trim', explode(',', $encodingList));
  377. }
  378. $encodingList = array_map('strtoupper', $encodingList);
  379. }
  380. foreach ($encodingList as $enc) {
  381. switch ($enc) {
  382. case 'ASCII':
  383. if (!preg_match('/[\x80-\xFF]/', $str)) {
  384. return $enc;
  385. }
  386. break;
  387. case 'UTF8':
  388. case 'UTF-8':
  389. if (preg_match('//u', $str)) {
  390. return 'UTF-8';
  391. }
  392. break;
  393. default:
  394. if (0 === strncmp($enc, 'ISO-8859-', 9)) {
  395. return $enc;
  396. }
  397. }
  398. }
  399. return false;
  400. }
  401. public static function mb_detect_order($encodingList = null)
  402. {
  403. if (null === $encodingList) {
  404. return self::$encodingList;
  405. }
  406. if (!\is_array($encodingList)) {
  407. $encodingList = array_map('trim', explode(',', $encodingList));
  408. }
  409. $encodingList = array_map('strtoupper', $encodingList);
  410. foreach ($encodingList as $enc) {
  411. switch ($enc) {
  412. default:
  413. if (strncmp($enc, 'ISO-8859-', 9)) {
  414. return false;
  415. }
  416. // no break
  417. case 'ASCII':
  418. case 'UTF8':
  419. case 'UTF-8':
  420. }
  421. }
  422. self::$encodingList = $encodingList;
  423. return true;
  424. }
  425. public static function mb_strlen($s, $encoding = null)
  426. {
  427. $encoding = self::getEncoding($encoding);
  428. if ('CP850' === $encoding || 'ASCII' === $encoding) {
  429. return \strlen($s);
  430. }
  431. return @iconv_strlen($s, $encoding);
  432. }
  433. public static function mb_strpos($haystack, $needle, $offset = 0, $encoding = null)
  434. {
  435. $encoding = self::getEncoding($encoding);
  436. if ('CP850' === $encoding || 'ASCII' === $encoding) {
  437. return strpos($haystack, $needle, $offset);
  438. }
  439. $needle = (string) $needle;
  440. if ('' === $needle) {
  441. if (80000 > \PHP_VERSION_ID) {
  442. trigger_error(__METHOD__.': Empty delimiter', \E_USER_WARNING);
  443. return false;
  444. }
  445. return 0;
  446. }
  447. return iconv_strpos($haystack, $needle, $offset, $encoding);
  448. }
  449. public static function mb_strrpos($haystack, $needle, $offset = 0, $encoding = null)
  450. {
  451. $encoding = self::getEncoding($encoding);
  452. if ('CP850' === $encoding || 'ASCII' === $encoding) {
  453. return strrpos($haystack, $needle, $offset);
  454. }
  455. if ($offset != (int) $offset) {
  456. $offset = 0;
  457. } elseif ($offset = (int) $offset) {
  458. if ($offset < 0) {
  459. if (0 > $offset += self::mb_strlen($needle)) {
  460. $haystack = self::mb_substr($haystack, 0, $offset, $encoding);
  461. }
  462. $offset = 0;
  463. } else {
  464. $haystack = self::mb_substr($haystack, $offset, 2147483647, $encoding);
  465. }
  466. }
  467. $pos = '' !== $needle || 80000 > \PHP_VERSION_ID
  468. ? iconv_strrpos($haystack, $needle, $encoding)
  469. : self::mb_strlen($haystack, $encoding);
  470. return false !== $pos ? $offset + $pos : false;
  471. }
  472. public static function mb_str_split($string, $split_length = 1, $encoding = null)
  473. {
  474. if (null !== $string && !\is_scalar($string) && !(\is_object($string) && method_exists($string, '__toString'))) {
  475. trigger_error('mb_str_split() expects parameter 1 to be string, '.\gettype($string).' given', \E_USER_WARNING);
  476. return null;
  477. }
  478. if (1 > $split_length = (int) $split_length) {
  479. if (80000 > \PHP_VERSION_ID) {
  480. trigger_error('The length of each segment must be greater than zero', \E_USER_WARNING);
  481. return false;
  482. }
  483. throw new \ValueError('Argument #2 ($length) must be greater than 0');
  484. }
  485. if (null === $encoding) {
  486. $encoding = mb_internal_encoding();
  487. }
  488. if ('UTF-8' === $encoding = self::getEncoding($encoding)) {
  489. $rx = '/(';
  490. while (65535 < $split_length) {
  491. $rx .= '.{65535}';
  492. $split_length -= 65535;
  493. }
  494. $rx .= '.{'.$split_length.'})/us';
  495. return preg_split($rx, $string, -1, \PREG_SPLIT_DELIM_CAPTURE | \PREG_SPLIT_NO_EMPTY);
  496. }
  497. $result = [];
  498. $length = mb_strlen($string, $encoding);
  499. for ($i = 0; $i < $length; $i += $split_length) {
  500. $result[] = mb_substr($string, $i, $split_length, $encoding);
  501. }
  502. return $result;
  503. }
  504. public static function mb_strtolower($s, $encoding = null)
  505. {
  506. return self::mb_convert_case($s, \MB_CASE_LOWER, $encoding);
  507. }
  508. public static function mb_strtoupper($s, $encoding = null)
  509. {
  510. return self::mb_convert_case($s, \MB_CASE_UPPER, $encoding);
  511. }
  512. public static function mb_substitute_character($c = null)
  513. {
  514. if (null === $c) {
  515. return 'none';
  516. }
  517. if (0 === strcasecmp($c, 'none')) {
  518. return true;
  519. }
  520. if (80000 > \PHP_VERSION_ID) {
  521. return false;
  522. }
  523. if (\is_int($c) || 'long' === $c || 'entity' === $c) {
  524. return false;
  525. }
  526. throw new \ValueError('Argument #1 ($substitute_character) must be "none", "long", "entity" or a valid codepoint');
  527. }
  528. public static function mb_substr($s, $start, $length = null, $encoding = null)
  529. {
  530. $encoding = self::getEncoding($encoding);
  531. if ('CP850' === $encoding || 'ASCII' === $encoding) {
  532. return (string) substr($s, $start, null === $length ? 2147483647 : $length);
  533. }
  534. if ($start < 0) {
  535. $start = iconv_strlen($s, $encoding) + $start;
  536. if ($start < 0) {
  537. $start = 0;
  538. }
  539. }
  540. if (null === $length) {
  541. $length = 2147483647;
  542. } elseif ($length < 0) {
  543. $length = iconv_strlen($s, $encoding) + $length - $start;
  544. if ($length < 0) {
  545. return '';
  546. }
  547. }
  548. return (string) iconv_substr($s, $start, $length, $encoding);
  549. }
  550. public static function mb_stripos($haystack, $needle, $offset = 0, $encoding = null)
  551. {
  552. [$haystack, $needle] = str_replace(self::SIMPLE_CASE_FOLD[0], self::SIMPLE_CASE_FOLD[1], [
  553. self::mb_convert_case($haystack, \MB_CASE_LOWER, $encoding),
  554. self::mb_convert_case($needle, \MB_CASE_LOWER, $encoding),
  555. ]);
  556. return self::mb_strpos($haystack, $needle, $offset, $encoding);
  557. }
  558. public static function mb_stristr($haystack, $needle, $part = false, $encoding = null)
  559. {
  560. $pos = self::mb_stripos($haystack, $needle, 0, $encoding);
  561. return self::getSubpart($pos, $part, $haystack, $encoding);
  562. }
  563. public static function mb_strrchr($haystack, $needle, $part = false, $encoding = null)
  564. {
  565. $encoding = self::getEncoding($encoding);
  566. if ('CP850' === $encoding || 'ASCII' === $encoding) {
  567. $pos = strrpos($haystack, $needle);
  568. } else {
  569. $needle = self::mb_substr($needle, 0, 1, $encoding);
  570. $pos = iconv_strrpos($haystack, $needle, $encoding);
  571. }
  572. return self::getSubpart($pos, $part, $haystack, $encoding);
  573. }
  574. public static function mb_strrichr($haystack, $needle, $part = false, $encoding = null)
  575. {
  576. $needle = self::mb_substr($needle, 0, 1, $encoding);
  577. $pos = self::mb_strripos($haystack, $needle, $encoding);
  578. return self::getSubpart($pos, $part, $haystack, $encoding);
  579. }
  580. public static function mb_strripos($haystack, $needle, $offset = 0, $encoding = null)
  581. {
  582. $haystack = self::mb_convert_case($haystack, \MB_CASE_LOWER, $encoding);
  583. $needle = self::mb_convert_case($needle, \MB_CASE_LOWER, $encoding);
  584. $haystack = str_replace(self::SIMPLE_CASE_FOLD[0], self::SIMPLE_CASE_FOLD[1], $haystack);
  585. $needle = str_replace(self::SIMPLE_CASE_FOLD[0], self::SIMPLE_CASE_FOLD[1], $needle);
  586. return self::mb_strrpos($haystack, $needle, $offset, $encoding);
  587. }
  588. public static function mb_strstr($haystack, $needle, $part = false, $encoding = null)
  589. {
  590. $pos = strpos($haystack, $needle);
  591. if (false === $pos) {
  592. return false;
  593. }
  594. if ($part) {
  595. return substr($haystack, 0, $pos);
  596. }
  597. return substr($haystack, $pos);
  598. }
  599. public static function mb_get_info($type = 'all')
  600. {
  601. $info = [
  602. 'internal_encoding' => self::$internalEncoding,
  603. 'http_output' => 'pass',
  604. 'http_output_conv_mimetypes' => '^(text/|application/xhtml\+xml)',
  605. 'func_overload' => 0,
  606. 'func_overload_list' => 'no overload',
  607. 'mail_charset' => 'UTF-8',
  608. 'mail_header_encoding' => 'BASE64',
  609. 'mail_body_encoding' => 'BASE64',
  610. 'illegal_chars' => 0,
  611. 'encoding_translation' => 'Off',
  612. 'language' => self::$language,
  613. 'detect_order' => self::$encodingList,
  614. 'substitute_character' => 'none',
  615. 'strict_detection' => 'Off',
  616. ];
  617. if ('all' === $type) {
  618. return $info;
  619. }
  620. if (isset($info[$type])) {
  621. return $info[$type];
  622. }
  623. return false;
  624. }
  625. public static function mb_http_input($type = '')
  626. {
  627. return false;
  628. }
  629. public static function mb_http_output($encoding = null)
  630. {
  631. return null !== $encoding ? 'pass' === $encoding : 'pass';
  632. }
  633. public static function mb_strwidth($s, $encoding = null)
  634. {
  635. $encoding = self::getEncoding($encoding);
  636. if ('UTF-8' !== $encoding) {
  637. $s = iconv($encoding, 'UTF-8//IGNORE', $s);
  638. }
  639. $s = preg_replace('/[\x{1100}-\x{115F}\x{2329}\x{232A}\x{2E80}-\x{303E}\x{3040}-\x{A4CF}\x{AC00}-\x{D7A3}\x{F900}-\x{FAFF}\x{FE10}-\x{FE19}\x{FE30}-\x{FE6F}\x{FF00}-\x{FF60}\x{FFE0}-\x{FFE6}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}]/u', '', $s, -1, $wide);
  640. return ($wide << 1) + iconv_strlen($s, 'UTF-8');
  641. }
  642. public static function mb_substr_count($haystack, $needle, $encoding = null)
  643. {
  644. return substr_count($haystack, $needle);
  645. }
  646. public static function mb_output_handler($contents, $status)
  647. {
  648. return $contents;
  649. }
  650. public static function mb_chr($code, $encoding = null)
  651. {
  652. if (0x80 > $code %= 0x200000) {
  653. $s = \chr($code);
  654. } elseif (0x800 > $code) {
  655. $s = \chr(0xC0 | $code >> 6).\chr(0x80 | $code & 0x3F);
  656. } elseif (0x10000 > $code) {
  657. $s = \chr(0xE0 | $code >> 12).\chr(0x80 | $code >> 6 & 0x3F).\chr(0x80 | $code & 0x3F);
  658. } else {
  659. $s = \chr(0xF0 | $code >> 18).\chr(0x80 | $code >> 12 & 0x3F).\chr(0x80 | $code >> 6 & 0x3F).\chr(0x80 | $code & 0x3F);
  660. }
  661. if ('UTF-8' !== $encoding = self::getEncoding($encoding)) {
  662. $s = mb_convert_encoding($s, $encoding, 'UTF-8');
  663. }
  664. return $s;
  665. }
  666. public static function mb_ord($s, $encoding = null)
  667. {
  668. if ('UTF-8' !== $encoding = self::getEncoding($encoding)) {
  669. $s = mb_convert_encoding($s, 'UTF-8', $encoding);
  670. }
  671. if (1 === \strlen($s)) {
  672. return \ord($s);
  673. }
  674. $code = ($s = unpack('C*', substr($s, 0, 4))) ? $s[1] : 0;
  675. if (0xF0 <= $code) {
  676. return (($code - 0xF0) << 18) + (($s[2] - 0x80) << 12) + (($s[3] - 0x80) << 6) + $s[4] - 0x80;
  677. }
  678. if (0xE0 <= $code) {
  679. return (($code - 0xE0) << 12) + (($s[2] - 0x80) << 6) + $s[3] - 0x80;
  680. }
  681. if (0xC0 <= $code) {
  682. return (($code - 0xC0) << 6) + $s[2] - 0x80;
  683. }
  684. return $code;
  685. }
  686. public static function mb_str_pad(string $string, int $length, string $pad_string = ' ', int $pad_type = \STR_PAD_RIGHT, ?string $encoding = null): string
  687. {
  688. if (!\in_array($pad_type, [\STR_PAD_RIGHT, \STR_PAD_LEFT, \STR_PAD_BOTH], true)) {
  689. throw new \ValueError('mb_str_pad(): Argument #4 ($pad_type) must be STR_PAD_LEFT, STR_PAD_RIGHT, or STR_PAD_BOTH');
  690. }
  691. if (null === $encoding) {
  692. $encoding = self::mb_internal_encoding();
  693. } else {
  694. self::assertEncoding($encoding, 'mb_str_pad(): Argument #5 ($encoding) must be a valid encoding, "%s" given');
  695. }
  696. if (self::mb_strlen($pad_string, $encoding) <= 0) {
  697. throw new \ValueError('mb_str_pad(): Argument #3 ($pad_string) must be a non-empty string');
  698. }
  699. $paddingRequired = $length - self::mb_strlen($string, $encoding);
  700. if ($paddingRequired < 1) {
  701. return $string;
  702. }
  703. switch ($pad_type) {
  704. case \STR_PAD_LEFT:
  705. return self::mb_substr(str_repeat($pad_string, $paddingRequired), 0, $paddingRequired, $encoding).$string;
  706. case \STR_PAD_RIGHT:
  707. return $string.self::mb_substr(str_repeat($pad_string, $paddingRequired), 0, $paddingRequired, $encoding);
  708. default:
  709. $leftPaddingLength = floor($paddingRequired / 2);
  710. $rightPaddingLength = $paddingRequired - $leftPaddingLength;
  711. return self::mb_substr(str_repeat($pad_string, $leftPaddingLength), 0, $leftPaddingLength, $encoding).$string.self::mb_substr(str_repeat($pad_string, $rightPaddingLength), 0, $rightPaddingLength, $encoding);
  712. }
  713. }
  714. public static function mb_ucfirst(string $string, ?string $encoding = null): string
  715. {
  716. if (null === $encoding) {
  717. $encoding = self::mb_internal_encoding();
  718. } else {
  719. self::assertEncoding($encoding, 'mb_ucfirst(): Argument #2 ($encoding) must be a valid encoding, "%s" given');
  720. }
  721. $firstChar = mb_substr($string, 0, 1, $encoding);
  722. $firstChar = mb_convert_case($firstChar, \MB_CASE_TITLE, $encoding);
  723. return $firstChar.mb_substr($string, 1, null, $encoding);
  724. }
  725. public static function mb_lcfirst(string $string, ?string $encoding = null): string
  726. {
  727. if (null === $encoding) {
  728. $encoding = self::mb_internal_encoding();
  729. } else {
  730. self::assertEncoding($encoding, 'mb_lcfirst(): Argument #2 ($encoding) must be a valid encoding, "%s" given');
  731. }
  732. $firstChar = mb_substr($string, 0, 1, $encoding);
  733. $firstChar = mb_convert_case($firstChar, \MB_CASE_LOWER, $encoding);
  734. return $firstChar.mb_substr($string, 1, null, $encoding);
  735. }
  736. private static function getSubpart($pos, $part, $haystack, $encoding)
  737. {
  738. if (false === $pos) {
  739. return false;
  740. }
  741. if ($part) {
  742. return self::mb_substr($haystack, 0, $pos, $encoding);
  743. }
  744. return self::mb_substr($haystack, $pos, null, $encoding);
  745. }
  746. private static function html_encoding_callback(array $m)
  747. {
  748. $i = 1;
  749. $entities = '';
  750. $m = unpack('C*', htmlentities($m[0], \ENT_COMPAT, 'UTF-8'));
  751. while (isset($m[$i])) {
  752. if (0x80 > $m[$i]) {
  753. $entities .= \chr($m[$i++]);
  754. continue;
  755. }
  756. if (0xF0 <= $m[$i]) {
  757. $c = (($m[$i++] - 0xF0) << 18) + (($m[$i++] - 0x80) << 12) + (($m[$i++] - 0x80) << 6) + $m[$i++] - 0x80;
  758. } elseif (0xE0 <= $m[$i]) {
  759. $c = (($m[$i++] - 0xE0) << 12) + (($m[$i++] - 0x80) << 6) + $m[$i++] - 0x80;
  760. } else {
  761. $c = (($m[$i++] - 0xC0) << 6) + $m[$i++] - 0x80;
  762. }
  763. $entities .= '&#'.$c.';';
  764. }
  765. return $entities;
  766. }
  767. private static function title_case(array $s)
  768. {
  769. return self::mb_convert_case($s[1], \MB_CASE_UPPER, 'UTF-8').self::mb_convert_case($s[2], \MB_CASE_LOWER, 'UTF-8');
  770. }
  771. private static function getData($file)
  772. {
  773. if (file_exists($file = __DIR__.'/Resources/unidata/'.$file.'.php')) {
  774. return require $file;
  775. }
  776. return false;
  777. }
  778. private static function getEncoding($encoding)
  779. {
  780. if (null === $encoding) {
  781. return self::$internalEncoding;
  782. }
  783. if ('UTF-8' === $encoding) {
  784. return 'UTF-8';
  785. }
  786. $encoding = strtoupper($encoding);
  787. if ('8BIT' === $encoding || 'BINARY' === $encoding) {
  788. return 'CP850';
  789. }
  790. if ('UTF8' === $encoding) {
  791. return 'UTF-8';
  792. }
  793. return $encoding;
  794. }
  795. public static function mb_trim(string $string, ?string $characters = null, ?string $encoding = null): string
  796. {
  797. return self::mb_internal_trim('{^[%s]+|[%1$s]+$}Du', $string, $characters, $encoding, __FUNCTION__);
  798. }
  799. public static function mb_ltrim(string $string, ?string $characters = null, ?string $encoding = null): string
  800. {
  801. return self::mb_internal_trim('{^[%s]+}Du', $string, $characters, $encoding, __FUNCTION__);
  802. }
  803. public static function mb_rtrim(string $string, ?string $characters = null, ?string $encoding = null): string
  804. {
  805. return self::mb_internal_trim('{[%s]+$}D', $string, $characters, $encoding, __FUNCTION__);
  806. }
  807. private static function mb_internal_trim(string $regex, string $string, ?string $characters, ?string $encoding, string $function): string
  808. {
  809. if (null === $encoding) {
  810. $encoding = self::mb_internal_encoding();
  811. } else {
  812. self::assertEncoding($encoding, $function.'(): Argument #3 ($encoding) must be a valid encoding, "%s" given');
  813. }
  814. if ('' === $characters) {
  815. return null === $encoding ? $string : self::mb_convert_encoding($string, $encoding);
  816. }
  817. if ('UTF-8' === $encoding) {
  818. $encoding = null;
  819. if (!preg_match('//u', $string)) {
  820. $string = @iconv('UTF-8', 'UTF-8//IGNORE', $string);
  821. }
  822. if (null !== $characters && !preg_match('//u', $characters)) {
  823. $characters = @iconv('UTF-8', 'UTF-8//IGNORE', $characters);
  824. }
  825. } else {
  826. $string = iconv($encoding, 'UTF-8//IGNORE', $string);
  827. if (null !== $characters) {
  828. $characters = iconv($encoding, 'UTF-8//IGNORE', $characters);
  829. }
  830. }
  831. if (null === $characters) {
  832. $characters = "\\0 \f\n\r\t\v\u{00A0}\u{1680}\u{2000}\u{2001}\u{2002}\u{2003}\u{2004}\u{2005}\u{2006}\u{2007}\u{2008}\u{2009}\u{200A}\u{2028}\u{2029}\u{202F}\u{205F}\u{3000}\u{0085}\u{180E}";
  833. } else {
  834. $characters = preg_quote($characters);
  835. }
  836. $string = preg_replace(sprintf($regex, $characters), '', $string);
  837. if (null === $encoding) {
  838. return $string;
  839. }
  840. return iconv('UTF-8', $encoding.'//IGNORE', $string);
  841. }
  842. private static function assertEncoding(string $encoding, string $errorFormat): void
  843. {
  844. try {
  845. $validEncoding = @self::mb_check_encoding('', $encoding);
  846. } catch (\ValueError $e) {
  847. throw new \ValueError(sprintf($errorFormat, $encoding));
  848. }
  849. // BC for PHP 7.3 and lower
  850. if (!$validEncoding) {
  851. throw new \ValueError(sprintf($errorFormat, $encoding));
  852. }
  853. }
  854. }