_make_url_clickable_cb()
云策文档标注
概述
_make_url_clickable_cb() 是一个回调函数,用于将 URI 匹配转换为 HTML A 元素。该函数从 WordPress 2.5.0 向后移植到 2.3.2 版本,作为 make_clickable() 的正则表达式回调。
关键要点
- 函数用途:将 URI 匹配转换为 HTML A 元素,用于 make_clickable() 中处理 URL 链接。
- 参数:接受一个数组 $matches,包含正则匹配结果。
- 返回值:返回包含 URI 地址的 HTML A 元素字符串。
- 版本历史:在 WordPress 2.3.2 中引入。
代码示例
function _make_url_clickable_cb( $matches ) {
$url = $matches[2];
if ( ')' === $matches[3] && strpos( $url, '(' ) ) {
/*
* If the trailing character is a closing parenthesis, and the URL has an opening parenthesis in it,
* add the closing parenthesis to the URL. Then we can let the parenthesis balancer do its thing below.
*/
$url .= $matches[3];
$suffix = '';
} else {
$suffix = $matches[3];
}
if ( isset( $matches[4] ) && ! empty( $matches[4] ) ) {
$url .= $matches[4];
}
// Include parentheses in the URL only if paired.
while ( substr_count( $url, '(' ) < substr_count( $url, ')' ) ) {
$suffix = ')' . $suffix;
$url = substr( $url, 0, -1 );
}
$url = esc_url( $url );
if ( empty( $url ) ) {
return $matches[0];
}
return "<a href="$url">$url</a>" . $suffix;
}注意事项
- 该函数是内部辅助函数,通常不直接调用,而是通过 make_clickable() 使用。
- 处理 URL 时,会检查括号配对,确保 HTML 结构正确。
- 使用 esc_url() 清理 URL,增强安全性。
原文内容
Callback to convert URI match to HTML A element.
Description
This function was backported from 2.5.0 to 2.3.2. Regex callback for make_clickable() .
Parameters
$matchesarrayrequired-
Single Regex Match.
Source
function _make_url_clickable_cb( $matches ) {
$url = $matches[2];
if ( ')' === $matches[3] && strpos( $url, '(' ) ) {
/*
* If the trailing character is a closing parenthesis, and the URL has an opening parenthesis in it,
* add the closing parenthesis to the URL. Then we can let the parenthesis balancer do its thing below.
*/
$url .= $matches[3];
$suffix = '';
} else {
$suffix = $matches[3];
}
if ( isset( $matches[4] ) && ! empty( $matches[4] ) ) {
$url .= $matches[4];
}
// Include parentheses in the URL only if paired.
while ( substr_count( $url, '(' ) < substr_count( $url, ')' ) ) {
$suffix = strrchr( $url, ')' ) . $suffix;
$url = substr( $url, 0, strrpos( $url, ')' ) );
}
$url = esc_url( $url );
if ( empty( $url ) ) {
return $matches[0];
}
$rel_attr = _make_clickable_rel_attr( $url );
return $matches[1] . "<a href="{$url}"{$rel_attr}>{$url}</a>" . $suffix;
}
Changelog
| Version | Description |
|---|---|
| 2.3.2 | Introduced. |