utf8_uri_encode

Encode the Unicode values to be used in the URI.

Description

(string) utf8_uri_encode( (string) $utf8_string, (int) $length = 0 ); 

Returns (string)

String with Unicode encoded for URI.

Parameters (2)

0. $utf8_string (string)
The utf8 string.
1. $length — Optional. (int)
Max length of the string

Usage

  1. if ( !function_exists( 'utf8_uri_encode' ) ) { 
  2. require_once ABSPATH . WPINC . '/formatting.php'; 
  3.  
  4. // The utf8 string. 
  5. $utf8_string = ''; 
  6.  
  7. // Max length of the string 
  8. $length = -1; 
  9.  
  10. // NOTICE! Understand what this does before running. 
  11. $result = utf8_uri_encode($utf8_string, $length); 
  12.  

Defined (1)

The function is defined in the following location(s).

/wp-includes/formatting.php  
  1. function utf8_uri_encode( $utf8_string, $length = 0 ) { 
  2. $unicode = ''; 
  3. $values = array(); 
  4. $num_octets = 1; 
  5. $unicode_length = 0; 
  6.  
  7. $string_length = strlen( $utf8_string ); 
  8.  
  9. for ($i = 0; $i < $string_length; $i++ ) { 
  10.  
  11. $value = ord( $utf8_string[ $i ] ); 
  12.  
  13. if ( $value < 128 ) { 
  14. if ( $length && ( $unicode_length >= $length ) ) 
  15. break; 
  16. $unicode .= chr($value); 
  17. $unicode_length++; 
  18. } else { 
  19. if ( count( $values ) == 0 ) { 
  20. if ( $value < 224 ) { 
  21. $num_octets = 2; 
  22. } elseif ( $value < 240 ) { 
  23. $num_octets = 3; 
  24. } else { 
  25. $num_octets = 4; 
  26.  
  27. $values[] = $value; 
  28.  
  29. if ( $length && ( $unicode_length + ($num_octets * 3) ) > $length ) 
  30. break; 
  31. if ( count( $values ) == $num_octets ) { 
  32. for ( $j = 0; $j < $num_octets; $j++ ) { 
  33. $unicode .= '%' . dechex( $values[ $j ] ); 
  34.  
  35. $unicode_length += $num_octets * 3; 
  36.  
  37. $values = array(); 
  38. $num_octets = 1; 
  39.  
  40. return $unicode;