wp_normalize_path()WP 3.9.0

Normalize a filesystem path.

On windows systems, replaces backslashes with forward slashes and forces upper-case drive letters. Allows for two leading slashes for Windows network shares, but ensures that all other duplicate slashes are reduced to a single.

1 time — 0.000001 sec (speed of light) | 50000 times — 0.05 sec (speed of light) | PHP 7.3.12, WP 5.3.2

No Hooks.

Return

String. Normalized path.

Usage

wp_normalize_path( $path );
$path(string) (required)
Path to normalize.

Examples

0

#1 Make sure the path to the file is correct

Suppose we are developing a file path and we need to make sure there are no double slashes or backslashes in the path. To do this we pass the resulting path through wp_normalize_path():

echo wp_normalize_path( '\www\site.com\wp-content\/\uploads//file.jpg' );
// output: /www/site.com/wp-content/uploads/file.jpg

echo wp_normalize_path( 'https://test.com//something/' ); 
// outputs: https://test.com/something/

echo wp_normalize_path( '//test.com//something/' ); 
// output: //test.com/something/

Changelog

Since 3.9.0 Introduced.
Since 4.4.0 Ensures upper-case drive letters on Windows systems.
Since 4.5.0 Allows for Windows network shares.
Since 4.9.7 Allows for PHP file wrappers.

Code of wp_normalize_path() WP 6.0.1

function wp_normalize_path( $path ) {
	$wrapper = '';

	if ( wp_is_stream( $path ) ) {
		list( $wrapper, $path ) = explode( '://', $path, 2 );

		$wrapper .= '://';
	}

	// Standardize all paths to use '/'.
	$path = str_replace( '\\', '/', $path );

	// Replace multiple slashes down to a singular, allowing for network shares having two slashes.
	$path = preg_replace( '|(?<=.)/+|', '/', $path );

	// Windows paths should uppercase the drive letter.
	if ( ':' === substr( $path, 1, 1 ) ) {
		$path = ucfirst( $path );
	}

	return $wrapper . $path;
}