esc_url( string $url, string[] $protocols = null, string $_context = 'display' )
检查并清除URL。
Checks and cleans a URL.
说明(Description)
从URL中删除了一些字符。如果URL用于显示(默认行为),则还将替换与号。“clean_url”筛选器将应用于返回的已清除url。
参数(Parameters)
参数 | 类型 | 必填 | 说明 |
---|---|---|---|
$url | (string) | 必需 | 要清除的URL。 |
$protocols | (string[]) | 可选 | 一系列可接受的协议。默认返回wp_allowed_protocols()的值 |
$_context | (string) | 可选 | 私人的。使用esc_url_raw()来使用数据库。 |
返回(Return)
(string)应用“clean_url”筛选器后清除的$url。源码(Source)
/**
* Checks and cleans a URL.
*
* A number of characters are removed from the URL. If the URL is for displaying
* (the default behaviour) ampersands are also replaced. The 'clean_url' filter
* is applied to the returned cleaned URL.
*
* @since 2.8.0
*
* @param string $url The URL to be cleaned.
* @param array $protocols Optional. An array of acceptable protocols.
* Defaults to return value of wp_allowed_protocols()
* @param string $_context Private. Use esc_url_raw() for database usage.
* @return string The cleaned $url after the 'clean_url' filter is applied.
*/
function esc_url( $url, $protocols = null, $_context = 'display' ) {
$original_url = $url;
if ( '' == $url )
return $url;
$url = preg_replace('|[^a-z0-9-~+_.?#=!&;,/:%@$|*'()\x80-\xff]|i', '', $url);
if ( 0 !== stripos( $url, 'mailto:' ) ) {
$strip = array('%0d', '%0a', '%0D', '%0A');
$url = _deep_replace($strip, $url);
}
$url = str_replace(';//', '://', $url);
/* If the URL doesn't appear to contain a scheme, we
* presume it needs http:// appended (unless a relative
* link starting with /, # or ? or a php file).
*/
if ( strpos($url, ':') === false && ! in_array( $url[0], array( '/', '#', '?' ) ) &&
! preg_match('/^[a-z0-9-]+?.php/i', $url) )
$url = 'http://' . $url;
// Replace ampersands and single quotes only when displaying.
if ( 'display' == $_context ) {
$url = wp_kses_normalize_entities( $url );
$url = str_replace( '&', '&', $url );
$url = str_replace( "'", ''', $url );
}
if ( '/' === $url[0] ) {
$good_protocol_url = $url;
} else {
if ( ! is_array( $protocols ) )
$protocols = wp_allowed_protocols();
$good_protocol_url = wp_kses_bad_protocol( $url, $protocols );
if ( strtolower( $good_protocol_url ) != strtolower( $url ) )
return '';
}
/**
* Filter a string cleaned and escaped for output as a URL.
*
* @since 2.3.0
*
* @param string $good_protocol_url The cleaned URL to be returned.
* @param string $original_url The URL prior to cleaning.
* @param string $_context If 'display', replace ampersands and single quotes only.
*/
return apply_filters( 'clean_url', $good_protocol_url, $original_url, $_context );
}
更新版本 | 源码位置 | 使用 | 被使用 |
---|---|---|---|
2.8.0 | wp-includes/formatting.php:4289 | 270 | 8 |
笔记(Notes)
添加指向主页的链接如果URI协议不是允许的协议之一,则esc_url()的结果是空字符串。WordPress允许的默认协议列表可以用以下代码扩展: