PHP Development

PHP Combine Path

PHP Combine Path, roughly equivalent to .Net’s Path.Combine where this combines two strings as path, handling when to place separators between two strings.

PHP Combine Path is a simple function I created that is roughly equivalent to Microsoft .NET’s Path.Combine method. This function combines two strings into a path. However, this only handles when to place path separators in between the two strings given, whether given string is a valid path or not.

It works by trimming off separator characters on the left side of $path1 and the right side of $path2, which is then concatenated as $path1, the directory separator character, and $path2. The function also works with URLs.

if (!function_exists('str_combinepath')){
 * Combines two strings into a path.
 * @param string $path1 : The first path to combine.
 * @param string $path2 : The second path to combine.
 * @param string $separator : (Optional) The directory separator. Default: OS specified.
function str_combinepath($path1, $path2, $separator = DIRECTORY_SEPARATOR){
	$path1 = rtrim($path1, $separator);
	$path2 = ltrim($path2, $separator);
	return $path1 . $separator . $path2;


str_combinepath ('/home', 'usr/');
// Result: '/home/usr/'

str_combinepath ('/home/', 'usr/');
// Result: '/home/usr/'

str_combinepath ('c:\temp', 'subdir\file.txt', '\\');
// Result: 'C:\temp\subdir\file.txt'

// Also works for URL's
str_combinepath ('', 'wp-admin', '/');
// Result:

You can see more of my PHP gists here.

Image Taken at Suzhou, Jiangsu, China, edited with Prisma AI.