Hallo,
falls der ein oder andere es mal benötigen sollte, dieses Skript
prüft, ob zwei übergebene Pfade Überschneidungen haben, wenn man sie zusammenschiebt. Algorithmisch so gelöst, path1 pro Schleifendurchlauf ein vorderer Pfad entfernt wird, path2 ein hinterer und diese Reste dann einfach per einfachem Array-Vergleich (==) verglichen werden.
Im Fehlerfall oder wenn einer der Pfade leer ist, wird false zurückgeliefert.
PHP-Code:
<?php
/**
* returns the path intersection between the two given paths
* path2 is moved from left to right until the pattern matches
*
* @example
* i = 0 :
* path1cut : path1/path2/path3
* path2cut : path2/path3/path4
* result : fail
*
* i = 1 :
* path1cut : path2/path3 [left path removed]
* path2cut : path2/path3 [right path removed]
* result : hit
*
* So the intersection between "path1/path2/path3" and
* "path2/path3/path4" is "path2/path3".
*
*
* @param string $path1 left path (f.e. an absolute path)
* @param string $path2 right path (f.e. a relative path)
* @param char $outputSeparator the matched path intersection will be concatenated with this char
* @return string|bool false in case of no intersection or empty path
*/
function getPathIntersection($path1, $path2, $outputSeparator = "/")
{
if (DIRECTORY_SEPARATOR != "/") {
$path1 = str_replace(DIRECTORY_SEPARATOR, "/", $path1);
$path2 = str_replace(DIRECTORY_SEPARATOR, "/", $path2);
}
$path1 = trim($path1, "/");
$path1Splitter = explode("/", $path1);
$path2 = trim($path2, "/");
$path2Splitter = explode("/", $path2);
if (empty($path1) || empty($path2)) {
return false;
}
for ($i = 0, $x = count($path1Splitter); $i < $x; ++$i) {
$path1SplitterCut = array_slice($path1Splitter, $i);
$path2SplitterCut = array_slice($path2Splitter, 0, $x - $i);
if ($path1SplitterCut == $path2SplitterCut) {
return implode($outputSeparator, $path1SplitterCut);
}
}
return false;
}
/*
assert(getPathIntersection("", "") === false);
assert(getPathIntersection("path1", "") === false);
assert(getPathIntersection("", "path1") === false);
assert(getPathIntersection("path2", "path1/path1") === false);
assert(getPathIntersection("path1/path2/path3", "path1/path2") === false);
assert(getPathIntersection("path1", "path1") === "path1");
assert(getPathIntersection("path1/path2", "path2/path1") === "path2");
assert(getPathIntersection("path1/path2", "path1/path2") === "path1/path2");
assert(getPathIntersection("path1", "path1/path2") === "path1");
assert(getPathIntersection("path1/path2", "path2") === "path2");
assert(getPathIntersection("path1/path2", "path2/path3/path4") === "path2");
assert(getPathIntersection("path1/path1/path1/path2", "path1/path1/path2/path2/path3") === "path1/path1/path2");
assert(getPathIntersection("path1/path2/path3/path2/path3", "path2/path3/path2/path3/path4") === "path2/path3/path2/path3");
assert(getPathIntersection("path1/path2", "path1/path2/path3") === "path1/path2");
*/
?>