Skip to content

Instantly share code, notes, and snippets.

@craiga
Last active December 13, 2015 23:29
Show Gist options
  • Save craiga/4991769 to your computer and use it in GitHub Desktop.
Save craiga/4991769 to your computer and use it in GitHub Desktop.
Enthusiastic URL encoding. URL encodes everything that's not an alphanumeric character.
<?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