函数文档

prep_atom_text_construct()

💡 云策文档标注

概述

prep_atom_text_construct() 函数用于根据 RFC 4287 标准,判断格式化数据字符串的类型,包括文本、HTML 或 XHTML。在 WordPress 中,文本定义为无标记,XHTML 为“格式良好”,HTML 为标签汤。

关键要点

  • 函数基于 RFC 4287 第 3.1 节定义类型:文本(无标记)、XHTML(格式良好)、HTML(标签汤)。
  • 对于 XHTML 值,根据第 3.1.1.3 节添加容器 div 标签。
  • 输入参数为字符串 $datastring,返回数组 array(type, value)。
  • 函数内部使用 str_contains() 和 xml_parse() 等方法来检测标记和验证 XML 结构。

代码示例

function prep_atom_text_construct( $data ) {
    if ( ! str_contains( $data, '<' ) && ! str_contains( $data, '>' ) && ! str_contains( $data, '&' ) ) {
        return array( 'text', $data );
    }
    if ( ! str_contains( $data, ']]>' ) ) {
        $parser = xml_parser_create();
        xml_parse( $parser, '<div>' . $data . '</div>', true );
        $code = xml_get_error_code( $parser );
        xml_parser_free( $parser );
        if ( PHP_VERSION_ID < 80000 && ! $code ) {
            return array( 'xhtml', '<div>' . $data . '</div>' );
        }
    }
    if ( ! str_contains( $data, ']]>' ) ) {
        return array( 'html', '' );
    } else {
        return array( 'html', htmlspecialchars( $data ) );
    }
}

注意事项

  • 函数在 WordPress 2.5.0 版本中引入。
  • 相关函数包括 wp_trigger_error() 和 __()。
  • 代码中处理了 PHP 版本兼容性问题(PHP_VERSION_ID < 80000)。

📄 原文内容

Determines the type of a string of data with the data formatted.

Description

Tell whether the type is text, HTML, or XHTML, per RFC 4287 section 3.1.

In the case of WordPress, text is defined as containing no markup, XHTML is defined as “well formed”, and HTML as tag soup (i.e., the rest).

Container div tags are added to XHTML values, per section 3.1.1.3.

Parameters

$datastringrequired
Input string.

Return

array array(type, value)

Source

function prep_atom_text_construct( $data ) {
	if ( ! str_contains( $data, '<' ) && ! str_contains( $data, '&' ) ) {
		return array( 'text', $data );
	}

	if ( ! function_exists( 'xml_parser_create' ) ) {
		wp_trigger_error( '', __( "PHP's XML extension is not available. Please contact your hosting provider to enable PHP's XML extension." ) );

		return array( 'html', "" );
	}

	$parser = xml_parser_create();
	xml_parse( $parser, '<div>' . $data . '</div>', true );
	$code = xml_get_error_code( $parser );

	if ( PHP_VERSION_ID < 80000 ) { // xml_parser_free() has no effect as of PHP 8.0.
		xml_parser_free( $parser );
	}

	unset( $parser );

	if ( ! $code ) {
		if ( ! str_contains( $data, '<' ) ) {
			return array( 'text', $data );
		} else {
			$data = "<div xmlns='http://www.w3.org/1999/xhtml'>$data</div>";
			return array( 'xhtml', $data );
		}
	}

	if ( ! str_contains( $data, ']]>' ) ) {
		return array( 'html', "" );
	} else {
		return array( 'html', htmlspecialchars( $data ) );
	}
}

Changelog

Version Description
2.5.0 Introduced.