如何在PHP中连续连接字符串?

时间:2014-12-02 08:20:02

标签: php

<?php

    $test = ' /clothing/men/tees';

    $req_url = explode('/', $test);

    $c = count($req_url);

    $ex_url = 'http://www.test.com/';

    for($i=1; $c > $i; $i++){

        echo '/'.'<a href="'.$ex_url.'/'.$req_url[$i].'">

                <span>'.ucfirst($req_url[$i]).'</span>

            </a>';
        //echo '<br/>'.$ex_url;....//last line
    }
?>

OUTPUT - 1 //在评论最后一行时

/ Clothing / Men / Tees

OUTPUT - 2 //取消评论最后一行$ ex_url显示

/ Clothing 
http://www.test.com// Men 
http://www.test.com// Tees 
http://www.test.com/

1。所需的输出 -

在span - / Clothing / Men / Tees和最后一个元素不应该是可点击的

和链接应该以这种方式创建

http://www.test.com/clothing/Men/tees -- when click on Tees

http://www.test.com/clothing/Men --  when click on Men

......分别

2。输出2为什么会出现

4 个答案:

答案 0 :(得分:2)

试试这个:

   <?php
    $test = '/clothing/men/tees';
    $url = 'http://www.test.com';
    foreach(preg_split('!/!', $test, -1,  PREG_SPLIT_NO_EMPTY) as $e) {
    $url .= '/'.$e;
        echo '/<a href="'.$url.'"><span>'.ucfirst($e).'</span></a>';
    }
    ?>

输出:

/Clothing/Men/Tees

HTML输出:

/<a href="http://www.test.com/clothing"><span>Clothing</span></a>/<a href="http://www.test.com/clothing/men"><span>Men</span></a>/<a href="http://www.test.com/clothing/men/tees"><span>Tees</span></a>

答案 1 :(得分:1)

尝试使用foreach()迭代数组,您必须跟踪网址后的路径。尝试它(测试和工作代码):

<?php

    $test = '/clothing/men/tees';
    $ex_url = 'http://www.test.com';
    $items = explode('/', $test);
    array_shift($items);

    $path = '';
    foreach($items as $item) {
        $path .= '/' . $item;
        echo '/ <a href="' . $ex_url . $path . '"><span>' . ucfirst($item) . '</span></a>';
    }

答案 2 :(得分:1)

试试这个。

<?php

$test = '/clothing/men/tees';
$req_url = explode('/', ltrim($test, '/'));
$ex_url = 'http://www.test.com/';

$stack = array();
$reuslt = array_map(function($part) use($ex_url, &$stack) {
    $stack[] = $part;
    return sprintf('<a href="%s%s">%s</a>', $ex_url, implode('/', $stack), ucfirst($part));
}, $req_url);


print_r($reuslt);

答案 3 :(得分:-1)

<?php
    $sTest= '/clothing/men/tees';
    $aUri= explode( '/', $sTest );
    $sBase= 'http://www.test.com';  // No trailing slash

    $sPath= $sBase;  // Will grow per loop iteration
    foreach( $aUri as $sDir ) {
        $sPath.= '/'. $sDir;
        echo ' / <a href="'. $sPath.'">'. ucfirst( $sDir ). '</a>';  // Unnecessary <span>
    }
?>