Last active
December 13, 2015 23:29
-
-
Save craiga/4991769 to your computer and use it in GitHub Desktop.
Enthusiastic URL encoding. URL encodes everything that's not an alphanumeric character.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Enthusiastically URL encode a string. | |
* | |
* URL encode everything that's not an alphanumeric character. | |
* | |
* @author Craig Anderson <[email protected]> | |
* @link https://gist.github.com/craiga/4991769#file-enthusiasticurlencode-php | |
*/ | |
function enthusiasticurlencode($s, $safeCharacters = null) { | |
if(is_null($safeCharacters)) { | |
$safeCharacters = array(); | |
$zeroCharacterCode = ord("0"); | |
$lowercaseACharacterCode = ord("a"); | |
$uppercaseACharacterCode = ord("A"); | |
for($characterCode = $zeroCharacterCode; $characterCode < $zeroCharacterCode + 10; $characterCode++) { | |
$safeCharacters[] = chr($characterCode); | |
} | |
for($characterCode = $lowercaseACharacterCode; $characterCode < $lowercaseACharacterCode + 26; $characterCode++) { | |
$safeCharacters[] = chr($characterCode); | |
} | |
for($characterCode = $uppercaseACharacterCode; $characterCode < $uppercaseACharacterCode + 26; $characterCode++) { | |
$safeCharacters[] = chr($characterCode); | |
} | |
} | |
$result = ""; | |
$characters = str_split($s); | |
foreach($characters as $character) { | |
if(in_array($character, $safeCharacters)) { | |
$result .= $character; | |
} | |
else { | |
$result .= "%" . strtoupper(base_convert(ord($character), 10, 16)); | |
} | |
} | |
return $result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment