Php首先拆分然后循环

时间:2018-02-20 18:23:58

标签: php loops for-loop split

我有一个这样的字符串:

$d = 'game, story, animation, video';

我想把它改成这样的结果:

<a href="game">game</a>, <a href="story">story</a>, <a href="animation">animation</a>, <a href="video">video</a>

所以我认为我必须将$ d拆分为&#39;,&#39;然后使用for循环。

我试过这个:

$d = 'game, story, animation, video';

list($a, $b, $c, $d) = explode(" ,", $d);

但如果我不知道有多少&#39;&#39;将会在那里,并达到预期的结果?

3 个答案:

答案 0 :(得分:1)

这里有很多方法可以实现。 通过使用foreach循环,您应该能够完成您尝试的操作。

您还需要正确地为数组项目分配,通过强制转换为字符串并使用[ ]简写或使用array()

$d = "game, story, animation, video";
$out = '' ;

foreach(explode(",",$d) as $item){
    $out .= "<a href='$item' />$item</a>";
}

echo $out;

如果您需要,,则可以使用此

$d = "game, story, animation, video";
$out = [] ;

foreach(explode(",",$d) as $item){
    $out []= "<a href='$item' />$item</a>";
}

echo implode(",",$out); 

在这里阅读更多

implode

explode

foreach

答案 1 :(得分:1)

这里的关键是要意识到你可以将这一行分为两部分:

list($a, $b, $c, $d) = explode(" ,", $d);

首先,它接受字符串$d并将其拆分为数组,让我们称之为$items

$items = explode(" ,", $d);

然后list()构造从该数组中获取项目并将它们放入单独的命名变量中:

list($a, $b, $c, $d) = $items;

如果您不知道列表中有多少项,您可以跳过第二步,并使用数组,可能使用foreach循环:

foreach ( $items as $item ) {
    echo "Doing something with '$item'...";
}

答案 2 :(得分:1)

<?php

$in  = 'game, story, animation, video';
$out = preg_replace('@([a-z]+)@', '<a href="$1">$1</a>', $in);
var_dump($out);

或者:

$tags = explode(',', $in);
$tags = array_map('trim', $tags);
$out  = [];
foreach($tags as $tag)
    $out[] = '<a href="' . $tag . '">' . $tag . '</a>';

$out = implode(', ', $out);
var_dump($out);

每个的输出:

string(112) "<a href="game">game</a>, <a href="story">story</a>, <a href="animation">animation</a>, <a href="video">video</a>"
相关问题