strip_fragment_from_url()WP 4.4.0

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

1 time — 0.000035 sec (very fast) | 50000 times — 0.20 sec (very fast)

No Hooks.

Return

String. The altered URL.

Usage

strip_fragment_from_url( $url );
$url(string) (required)
The URL to strip.

Examples

0

#1 Remove the hash (fragment, anchor) from the URL.

echo strip_fragment_from_url ( 'http://wp-kama.ru/foo#fooooo' );
// returns: http://wp-kama.ru/foo

echo strip_fragment_from_url ( 'http://wp-kama.ru/foo?foo=bar#fooooo' );
// returns: http://wp-kama.ru/foo?foo=bar

echo strip_fragment_from_url ( '/foo#fooooo' );
// will not process and returns as it was: /foo#fooooo

Changelog

Since 4.4.0 Introduced.

strip_fragment_from_url() code WP 6.4.3

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;
}