函数文档

get_url_in_content()

💡 云策文档标注

概述

get_url_in_content() 函数用于从传入的内容字符串中提取并返回第一个 URL。它通过 WP_HTML_Tag_Processor 解析 HTML 内容,查找 A 元素并获取其 href 属性值。

关键要点

  • 参数:$content(字符串,必需),可能包含带有非空 href 属性的 A 元素。
  • 返回值:如果找到 URL,则返回经过 sanitize_url() 处理的字符串;否则返回 false。
  • 内部实现:使用 WP_HTML_Tag_Processor 迭代查找 A 标签,并检查 href 属性是否非空字符串。
  • 相关函数:WP_HTML_Tag_Processor::__construct() 用于构造处理器,sanitize_url() 用于 URL 消毒。
  • 版本历史:自 WordPress 3.6.0 版本引入。

代码示例

function get_url_in_content( $content ) {
    if ( empty( $content ) ) {
        return false;
    }

    $processor = new WP_HTML_Tag_Processor( $content );
    while ( $processor->next_tag( 'A' ) ) {
        $href = $processor->get_attribute( 'href' );
        if ( is_string( $href ) && '' !== $href ) {
            return sanitize_url( $href );
        }
    }

    return false;
}

📄 原文内容

Extracts and returns the first URL from passed content.

Parameters

$contentstringrequired
A string which might contain an A element with a non-empty href attribute.

Return

string|false Database-escaped URL via esc_url() if found, otherwise false.

Source

function get_url_in_content( $content ) {
	if ( empty( $content ) ) {
		return false;
	}

	$processor = new WP_HTML_Tag_Processor( $content );
	while ( $processor->next_tag( 'A' ) ) {
		$href = $processor->get_attribute( 'href' );
		if ( is_string( $href ) && '' !== $href ) {
			return sanitize_url( $href );
		}
	}

	return false;
}

Changelog

Version Description
3.6.0 Introduced.