Data hosted with ♥ by Pastebin.com - Download Raw - See Original
  1. /**
  2.  * Encode the Unicode values to be used in the URI.
  3.  *
  4.  * @since 1.5.0
  5.  *
  6.  * @param string $utf8_string
  7.  * @param int $length Max length of the string
  8.  * @return string String with Unicode encoded for URI.
  9.  */
  10. function utf8_uri_encode( $utf8_string, $length = 0 ) {
  11.     $unicode = '';
  12.     $values = array();
  13.     $num_octets = 1;
  14.     $unicode_length = 0;
  15.  
  16.     $string_length = strlen( $utf8_string );
  17.     for ($i = 0; $i < $string_length; $i++ ) {
  18.  
  19.         $value = ord( $utf8_string[ $i ] );
  20.  
  21.         if ( $value < 128 ) {
  22.             if ( $length && ( $unicode_length >= $length ) )
  23.                 break;
  24.             $unicode .= chr($value);
  25.             $unicode_length++;
  26.         } else {
  27.             if ( count( $values ) == 0 ) $num_octets = ( $value < 224 ) ? 2 : 3;
  28.  
  29.             $values[] = $value;
  30.  
  31.             if ( $length && ( $unicode_length + ($num_octets * 3) ) > $length )
  32.                 break;
  33.             if ( count( $values ) == $num_octets ) {
  34.                 if ($num_octets == 3) {
  35.                     $unicode .= '%' . dechex($values[0]) . '%' . dechex($values[1]) . '%' . dechex($values[2]);
  36.                     $unicode_length += 9;
  37.                 } else {
  38.                     $unicode .= '%' . dechex($values[0]) . '%' . dechex($values[1]);
  39.                     $unicode_length += 6;
  40.                 }
  41.  
  42.                 $values = array();
  43.                 $num_octets = 1;
  44.             }
  45.         }
  46.     }
  47.  
  48.     return $unicode;
  49. }