PHP Combine Path

I created a simple function that is roughly equivalent to .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. 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.

General Usage

<?php
str_combinepath ( '/home' , 'usr/' );
// '/home/usr/'

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

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

str_combinepath ( 'https://www.earlpeter.com' , 'wp-admin', '/' );
// Also works for URL's
// https://www.earlpeter.com/wp-admin
Fork

Comments