Stuart Brian Stuart Brian - 1 month ago 5
PHP Question

Replace last element string after looking the string in php

How do I replace the last string after i have loop on each string?
I was able to do this but still not complete

// here my get string ?dir=hello1/hello2/hello3

if (isset($_GET['dir'])) {
$hrefTabs = $_GET['dir'];
if (!empty($hrefTabs)) {
$arrayOfhref = explode('/', $hrefTabs);//I explode string /

foreach ($arrayOfhref as $roothrefline) {
$trimstrhref = preg_replace('/\s+/', '', $roothrefline); // Here i trim white space

$mmhref = '<a href="'.$trimstrhref.'">'.$roothrefline.'</a> / '; // Here i assign each strin hyper reference

$toreplace = $roothrefline . ' / ';
$lastobj = substr_replace($mmhref, $toreplace, strlen($mmhref)); // here i want the last element not to have hyper reference attribut

echo $lastobj; // but i get this at output
//<a href="">hello1</a> / hello1 / <a href="">hello2</a> / hello2 /<a href="">hello3</a> / hello3
}
}
}


My out put look like this

<a href="">hello1</a> / hello1 / <a href="">hello2</a> / hello2 /<a
href="">hello3</a> / hello3


I want to have it look like this

<a href="">hello1</a> / <a href="">hello2</a> / hello3

Answer
$dir = "hello1/hello2/hello3";

  if(isset($dir)){
     $hrefTabs = $dir;
     if(!empty($hrefTabs)){
    $arrayOfhref = explode('/', $hrefTabs);//I explode string /
    $i = 0;
    foreach($arrayOfhref as $roothrefline) {
      $trimstrhref = preg_replace('/\s+/', '', $roothrefline); // Here i trim white space
      $mmhref = '<a href="'.$trimstrhref.'">'.$roothrefline.'</a> / '; // Here i assign each strin hyper reference
      $toreplace = $roothrefline . ' / ';

      if(++$i === count($arrayOfhref)){
        echo $roothrefline;
      } else {
        echo $mmhref;
      }
    }
  }

}

Something like this...