wp_normalize_path()WP 3.9.0

Normalizes the path for a file or folder by replacing backslashes and double slashes with a single one.

What the function does:

  • Replaces backslashes \ with forward slashes / (for cross-platform compatibility).
  • Converts the drive letter (in Windows) to uppercase (c:C:).
  • Removes duplicate slashes, except for network paths (//server/share remains).
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.

Returns

String. A cleaned (processed) string.

Usage

wp_normalize_path( $path ): string;
$path(string) (required)
The path to be processed.

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\example.com\wp-content\/\uploads//file.jpg' );
					//>> /www/example.com/wp-content/uploads/file.jpg

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

echo wp_normalize_path( '//test.com//something/' ); 
					//>> //test.com/something/

echo wp_normalize_path( 'c://some\/\path//file.jpg' ); 
					//>> C:/some/path/file.jpg

echo wp_normalize_path( 'c:/Projects\\api/\apilibrary.sln' ); 
					//>> C:/Projects/api/apilibrary.sln

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.
Since 7.0.0 Uses a static cache to store normalized paths.

wp_normalize_path() code WP 7.0

function wp_normalize_path( $path ): string {
	$path = (string) $path;

	static $cache = array();
	if ( isset( $cache[ $path ] ) ) {
		return $cache[ $path ];
	}

	$original_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 = (string) preg_replace( '|(?<=.)/+|', '/', $path );

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

	$cache[ $original_path ] = $wrapper . $path;
	return $cache[ $original_path ];
}