convert_chars()
云策文档标注
概述
convert_chars() 函数用于将字符串中的孤立 & 字符转换为 & 实体,以防止在 HTML 或 XML 中产生解析错误。该函数自 WordPress 0.71 版本引入,包含一个已弃用的参数。
关键要点
- 函数将字符串中的孤立 & 字符转换为 & 实体,确保在 HTML/XML 中正确显示。
- 接受两个参数:$content(必需,要转换的字符串)和 $deprecated(已弃用,自 0.71 版本起不再使用)。
- 使用正则表达式 preg_replace 进行转换,仅处理未形成有效 HTML 实体的 & 字符。
- 如果提供了 $deprecated 参数,会调用 _deprecated_argument() 发出弃用警告。
- 返回转换后的字符串。
代码示例
function convert_chars( $content, $deprecated = '' ) {
if ( ! empty( $deprecated ) ) {
_deprecated_argument( __FUNCTION__, '0.71' );
}
if ( str_contains( $content, '&' ) ) {
$content = preg_replace( '/&([^#])(?![a-z1-4]{1,8};)/i', '&$1', $content );
}
return $content;
}注意事项
- 该函数主要用于处理文本内容,以避免在输出到 HTML 或 RSS 时出现解析问题。
- 自 WordPress 0.71 版本起,$deprecated 参数已弃用,建议仅使用 $content 参数。
- 函数内部使用 str_contains 检查 & 字符存在,提高效率。
原文内容
Converts lone & characters into & (a.k.a. &)
Parameters
$contentstringrequired-
String of characters to be converted.
$deprecatedstringrequired-
Not used.
Source
function convert_chars( $content, $deprecated = '' ) {
if ( ! empty( $deprecated ) ) {
_deprecated_argument( __FUNCTION__, '0.71' );
}
if ( str_contains( $content, '&' ) ) {
$content = preg_replace( '/&([^#])(?![a-z1-4]{1,8};)/i', '&$1', $content );
}
return $content;
}
Changelog
| Version | Description |
|---|---|
| 0.71 | Introduced. |