函数文档

strip_fragment_from_url()

💡 云策文档标注

概述

strip_fragment_from_url() 函数用于从 URL 中移除 #fragment 部分,返回处理后的 URL。它通过 wp_parse_url() 解析 URL,并重构除 fragment 外的其他组件。

关键要点

  • 函数接受一个必需参数 $url,表示要处理的 URL 字符串
  • 返回值为移除 #fragment 后的 URL 字符串
  • 内部使用 wp_parse_url() 解析 URL,确保跨 PHP 版本的一致性
  • 重构 URL 时包含 scheme、host、port、path 和 query 组件,但排除 fragment

代码示例

function strip_fragment_from_url( $url ) {
    $parsed_url = wp_parse_url( $url );

    if ( ! empty( $parsed_url['host'] ) ) {
        $url = '';

        if ( ! empty( $parsed_url['scheme'] ) ) {
            $url = $parsed_url['scheme'] . ':';
        }

        $url .= '//' . $parsed_url['host'];

        if ( ! empty( $parsed_url['port'] ) ) {
            $url .= ':' . $parsed_url['port'];
        }

        if ( ! empty( $parsed_url['path'] ) ) {
            $url .= $parsed_url['path'];
        }

        if ( ! empty( $parsed_url['query'] ) ) {
            $url .= '?' . $parsed_url['query'];
        }
    }

    return $url;
}

注意事项

  • 函数在 WordPress 4.4.0 版本中引入
  • 主要用于 do_enclose() 和 redirect_canonical() 等函数中处理 URL
  • 仅当 URL 包含 host 时才进行重构,否则可能返回原 URL 或空字符串

📄 原文内容

Strips the #fragment from a URL, if one is present.

Parameters

$urlstringrequired
The URL to strip.

Return

string The altered URL.

Source

function strip_fragment_from_url( $url ) {
	$parsed_url = wp_parse_url( $url );

	if ( ! empty( $parsed_url['host'] ) ) {
		$url = '';

		if ( ! empty( $parsed_url['scheme'] ) ) {
			$url = $parsed_url['scheme'] . ':';
		}

		$url .= '//' . $parsed_url['host'];

		if ( ! empty( $parsed_url['port'] ) ) {
			$url .= ':' . $parsed_url['port'];
		}

		if ( ! empty( $parsed_url['path'] ) ) {
			$url .= $parsed_url['path'];
		}

		if ( ! empty( $parsed_url['query'] ) ) {
			$url .= '?' . $parsed_url['query'];
		}
	}

	return $url;
}

Changelog

Version Description
4.4.0 Introduced.