Jarla Jarla - 1 year ago 38
PHP Question

How can I replace/extract parts of a path?

This is my code:

$path = "monkey/cat/horse";
$linkPath = str_replace("/", "</a><br><a href='my page.html/".$path."'>", $path);
echo "<a href='my page.html/".$path."'>".$linkPath . "</a>";

On my page it outputs this:

<a href='my page.html/monkey/cat/horse'>monkey</a><br>
<a href='my page.html/monkey/cat/horse'>cat</a><br>
<a href='my page.html/monkey/cat/horse'>horse</a>

Now my problem is that if want the link to be only the path of the value. This means my desired result should be instead

<a href='my page.html/monkey'>monkey</a><br>
<a href='my page.html/monkey/cat'>cat</a><br>
<a href='my page.html/monkey/cat/horse'>horse</a>


str_replace() is not the right way to go.

$path = "monkey/cat/horse";

$level = '';
foreach(explode('/', $path) as $segment) {
   $level .= "/{$segment}";
   echo "<a href='my page.html{$level}'>{$segment}</a>";

would echo

<a href='my page.html/monkey'>monkey</a>
<a href='my page.html/monkey/cat'>cat</a>
<a href='my page.html/monkey/cat/horse'>horse</a>


is it possible to make the last segment not as a link

Yes it is, but you should try yourself first...

$level = '';
$tmp = explode('/', $path);
$count = count($tmp);
for($i=0; $i<($count-1); $i++) {
   $segment = $tmp[$i];
   $level .= "/{$tmp[$i]}";
   echo "<a href='my page.html{$level}'>{$tmp[$i]}</a>";
echo $tmp[$count-1];