note 102482 added to function.htmlentities

[email protected] Thu, 17 Feb 2011 01:01:41 -0800
Newsgroups php.notes
Message-ID <[email protected]>
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);
	}
----
Server IP: 195.221.21.36
Probable Submitter: 80.11.160.54
----
Manual Page -- http://www.php.net/manual/en/function.htmlentities.php
Edit        -- https://master.php.net/note/edit/102482
Del: integrated  -- https://master.php.net/note/delete/102482/integrated
Del: useless     -- https://master.php.net/note/delete/102482/useless
Del: bad code    -- https://master.php.net/note/delete/102482/bad+code
Del: spam        -- https://master.php.net/note/delete/102482/spam
Del: non-english -- https://master.php.net/note/delete/102482/non-english
Del: in docs     -- https://master.php.net/note/delete/102482/in+docs
Del: other reasons-- https://master.php.net/note/delete/102482
Reject      -- https://master.php.net/note/reject/102482
Search      -- https://master.php.net/manage/user-notes.php