1 <?php
2 
3 namespace Mpdf\Utils;
4 
5 class UtfString
6 {
7 
8 	/**
9 	 * Converts all the &#nnn; and &#xhhh; in a string to Unicode
10 	 *
11 	 * @since mPDF 5.7
12 	 * @param string $str
13 	 * @param bool $lo
14 	 *
15 	 * @return string
16 	 */
17 	public static function strcode2utf($str, $lo = true)
18 	{
19 		$str = preg_replace_callback('/\&\#(\d+)\;/m', function ($matches) use ($lo) {
20 			return static::code2utf($matches[1], $lo ? 1 : 0);
21 		}, $str);
22 		$str = preg_replace_callback('/\&\#x([0-9a-fA-F]+)\;/m', function ($matches) use ($lo) {
23 			return static::codeHex2utf($matches[1], $lo ? 1 : 0);
24 		}, $str);
25 
26 		return $str;
27 	}
28 
29 	/**
30 	 * @param int $num
31 	 * @param bool $lo
32 	 *
33 	 * @return string
34 	 */
35 	public static function code2utf($num, $lo = true)
36 	{
37 		// Returns the utf string corresponding to the unicode value
38 		if ($num < 128) {
39 			if ($lo) {
40 				return chr($num);
41 			}
42 			return '&#' . $num . ';';
43 		}
44 		if ($num < 2048) {
45 			return chr(($num >> 6) + 192) . chr(($num & 63) + 128);
46 		}
47 		if ($num < 65536) {
48 			return chr(($num >> 12) + 224) . chr((($num >> 6) & 63) + 128) . chr(($num & 63) + 128);
49 		}
50 		if ($num < 2097152) {
51 			return chr(($num >> 18) + 240) . chr((($num >> 12) & 63) + 128) . chr((($num >> 6) & 63) + 128) . chr(($num & 63) + 128);
52 		}
53 
54 		return '?';
55 	}
56 
57 	public static function codeHex2utf($hex, $lo = true)
58 	{
59 		$num = hexdec($hex);
60 		if (($num < 128) && !$lo) {
61 			return '&#x' . $hex . ';';
62 		}
63 
64 		return static::code2utf($num, $lo);
65 	}
66 
67 }
68