3v4l.org

run code in 300+ PHP versions simultaneously
<?php // PHP < 7.2 // https://github.com/symfony/polyfill-mbstring/blob/master/Mbstring.php#L708-L730 if( ! function_exists("mb_ord") ) { function mb_ord($s) { if (1 === \strlen($s)) { return \ord($s); } $code = ($s = unpack('C*', substr($s, 0, 4))) ? $s[1] : 0; if (0xF0 <= $code) { return (($code - 0xF0) << 18) + (($s[2] - 0x80) << 12) + (($s[3] - 0x80) << 6) + $s[4] - 0x80; } if (0xE0 <= $code) { return (($code - 0xE0) << 12) + (($s[2] - 0x80) << 6) + $s[3] - 0x80; } if (0xC0 <= $code) { return (($code - 0xC0) << 6) + $s[2] - 0x80; } return $code; } } function ord2seqlen($ord) { if($ord < 128){ return 1; } else if($ord < 224) { return 2; } else if($ord < 240) { return 3; } else if($ord < 248) { return 4; } else { throw new \Exception("No support for 5 or 6 byte sequences."); } } function utf8_seq_iter($input) { for($i=0,$c=strlen($input); $i<$c; ) { $bytes = ord2seqlen(ord($input[$i])); yield substr($input, $i, $bytes); $i += $bytes; } } function escape_codepoint($codepoint, $skip_low=true) { $ord = mb_ord($codepoint); if( $skip_low && $ord < 128 ) { return $codepoint; } else { return sprintf("\\u%04x", $ord); } } $input = "आए थे पर्यटक, खुद ही बह गए"; $output = ''; foreach( utf8_seq_iter($input) as $codepoint ) { $output .= escape_codepoint($codepoint); } var_dump($output);

preferences:
32.35 ms | 402 KiB | 5 Q