Zend - The PHP Company




I18N

Add Code


utf8RawUrlDecode  

Type: code fragment
Added by: ronen
Entered: 07/03/2002
Last modified: 07/12/2001
Rating: - (fewer than 3 votes)
Views: 7879
RFC1738 compliant alternative to PHP's rawurldecode, which actually works with unicode entities (using utf-8 encoding). Also included is a fix to the javascript method escape(), which ensures RFC1738 compliant encoding of strings containing utf-8 and/or ascii.


<?php
/**
* RFC1738 compliant replacement to PHP's rawurldecode - which actually works with unicode (using utf-8 encoding)
* @author Ronen Botzer
* @param $source [STRING]
* @return unicode safe rawurldecoded string [STRING]
* @access public
*/
function utf8RawUrlDecode ($source) {
    
$decodedStr '';
    
$pos 0;
    
$len strlen ($source);

    while (
$pos $len) {
        
$charAt substr ($source$pos1);
        if (
$charAt == '%') {
            
$pos++;
            
$charAt substr ($source$pos1);
            if (
$charAt == 'u') {
                
// we got a unicode character
                
$pos++;
                
$unicodeHexVal substr ($source$pos4);
                
$unicode hexdec ($unicodeHexVal);
                
$entity "&#"$unicode ';';
                
$decodedStr .= utf8Encode ($entity);
                
$pos += 4;
            }
            else {
                
// we have an escaped ascii character
                
$hexVal substr ($source$pos2);
                
$decodedStr .= chr (hexdec ($hexVal));
                
$pos += 2;
            }
        }
        else {
            
$decodedStr .= $charAt;
            
$pos++;
        }
    }

    return 
$decodedStr;
}




/**
* The following is actually a javascript method I had to write to replace escape().  
* escape() is the javascript method equivalent to PHP's rawurlencode(), however it doesn't encode utf-8 multibyte characters correctly in most browsers.
*/
// Warning: the following code is JavaScript.  Ugh.  :D
// use this instead of escape() to ensure a correctly encoded url string (RFC1738)
function urlEncode (str) {
    
len str.length;
    
res = new String();
    
charOrd = new Number();
    
    for (
0leni++) {
        
charOrd str.charCodeAt(i);
        if ((
charOrd >= 65 && charOrd <= 90) || (charOrd >= 97 && charOrd <= 122) || (charOrd >= 48 && charOrd <= 57) || (charOrd == 33) || (charOrd == 36) || (charOrd == 95)) {
            
// this is alphanumeric or $-_.+!*'(), which according to RFC1738 we don't escape
            
res += str.charAt(i);

        }
        else {
            
res += '%';
            if (
charOrd 255res += 'u';
            
hexValStr charOrd.toString(16);
            if ((
hexValStr.length) % == 1hexValStr '0' hexValStr;
            
res += hexValStr;
        }
    }

    return 
res;
}

?>


Usage Example




Rate This Script





Search



This Category All Categories