note 102482 deleted from function.htmlentities by danbrown

[email protected] Thu, 17 Feb 2011 08:16:54 -0800
Newsgroups php.notes
Message-ID <[email protected]>
Note Submitter: Barmasjulien at gmail dotCom 

----

I'm posting an updated version of silverbeat's original function, which converts 2-bytes characters without using htmlentities (buggy on my server) and convert it to urlencoding (http post curl-compatible):

function utf8ToEntitiesUrlencoded($utf8, $encodeTags=true)
	{
		$result = '';
		for ($i = 0; $i < strlen($utf8); $i++) {
			$char = $utf8[$i];
			$ascii = ord($char);
			if ($ascii < 128) {
				// one-byte character
				$result .= ($encodeTags) ? htmlentities($char) : $char;
			} else if ($ascii < 192) {
				// Non-utf8 char
			} else if ($ascii < 224) {
				// two-byte character
				$ascii1 = ord($utf8[$i+1]);
				$unicode = (63 & $ascii) * 64 +
						   (63 & $ascii1);
				$result .= "&#$unicode;";
				
				$i++;
			} else if ($ascii < 240) {
				// three-byte character
				$ascii1 = ord($utf8[$i+1]);
				$ascii2 = ord($utf8[$i+2]);
				$unicode = (15 & $ascii) * 4096 +
						   (63 & $ascii1) * 64 +
						   (63 & $ascii2);
				$result .= "&#$unicode;";
				$i += 2;
			} else if ($ascii < 248) {
				// four-byte character
				$ascii1 = ord($utf8[$i+1]);
				$ascii2 = ord($utf8[$i+2]);
				$ascii3 = ord($utf8[$i+3]);
				$unicode = (15 & $ascii) * 262144 +
						   (63 & $ascii1) * 4096 +
						   (63 & $ascii2) * 64 +
						   (63 & $ascii3);
				$result .= "&#$unicode;";
				$i += 3;
			}
		}

		// if you don't want to "light" urlencode, remove str_replaces:
		$result = str_replace("#", "%23", $result);
		$result = str_replace(";", "%3B", $result);		
		return str_replace("&", "%26", $result);
	}