在php中查找字符串后替换最后一个元素字符串

时间:2016-11-01 12:28:15

标签: php replace

如何在每个字符串上循环后替换最后一个字符串? 我能够做到这一点,但仍然没有完成

// 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
        }
    }
}

我的外观看起来像这样

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

我希望看起来像这样

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

2 个答案:

答案 0 :(得分:2)

在你的foreach之前

$lastElement = array_pop($arrayOfHref);

并在循环后显示$ lastElement。

http://php.net/manual/en/function.array-pop.php

答案 1 :(得分:0)

$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;
      }
    }
  }

}

像这样......