Well, letâs at least walk you through what it DOES. You can then figure out whether itâs a good idea to use it (though as benanamen points out⌠probably not.)
function esc_url($url) {
Define a function, esc_url, that takes one parameter, $url.
if ('' == $url) {
return $url;
}
If the URL was empty, return that empty string; weâre done here.
$url = preg_replace('|[^a-z0-9-~+_.?#=!&;,/:%@$\|*\'()\\x80-\\xff]|i', '', $url);
Get rid of any characters that are not:
alphabet characters,
the numbers 0-9,
the symbols -~+_.?#=!&;,/:%@$|*'()
the latin-1 characters corresponding to the hex-value range 80-FF. This is often called the âExtended ASCII Charactersâ.
(the |i indicates that the search should be case-insensitive, hence not needing to specify both a-z and A-Z.)
$strip = array('%0d', '%0a', '%0D', '%0A');
$url = (string) $url;
Setting up some variables for later use.
$count = 1;
while ($count) {
$url = str_replace($strip, '', $url, $count);
}
Recursively strip out anything in the $strip array from the URL. Repeat until you didnt remove anything.
For example, one of the elements of $strip is â%0dâ. If, however, I wrote my url to be â%0%0ddâ, running str_replace once would remove the inner %0d, replace it with a ââ, and cause the string to just be â%0dâ.
$url = str_replace(';//', '://', $url);
Change the semicolon to a colon in the URLâs protocol definition.
$url = htmlentities($url);
For some reason, we now convert special characters in the url to html entities.
$url = str_replace('&', '&', $url);
Remember the last line? Yeah, undo it for ampersands.
$url = str_replace("'", ''', $url);
This was probably supposed to replace single quotes with double quotes, as droop points out. But they flubbed it up.
if ($url[0] !== '/') {
// We're only interested in relative links from $_SERVER['PHP_SELF']
return '';
} else {
return $url;
}
If the first character of the URL is a /, itâs trying to refer to the root folder of the domain weâre currently on. The script doesnt want to play with those, so it returns the empty string if it finds one. If it starts with anything else, the URL is relative to the current scriptâs directory, so we return the URL.
This isnât actually correct; a URL that begins with, say, http://, is not relative to the current page; theyâre absolute URLâs. But the script doesnt seem to mind those, for whatever reason.