Php先拆分,然后进行for循环
我有这样一个字符串:Php先拆分,然后进行for循环,php,loops,for-loop,split,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 = 'game, story, animat
$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 = 'game, story, animation, video';
<a href="game">game</a>, <a href="story">story</a>, <a href="animation">animation</a>, <a href="video">video</a>
但是,如果我不知道有多少个',并达到预期的结果,我该如何分割它呢?有很多方法可以实现这一点,这里有一种。 通过使用
foreach
循环,您应该能够完成您试图完成的任务
您还需要通过将字符串转换为字符串并使用[]
速记或使用array()
在这里阅读更多
这里的关键是要意识到,你可以将这条线分成两部分:
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'...";
}
这会给你一个语法错误。我有$d=“游戏、故事、动画、视频”;《我是怎样的goona》将此更改为$d=[“游戏”、“故事”、“动画”、“视频”];我想游戏、故事、动画、视频只是一句话。我可以通过在字符串“,”上爆炸来删除数组映射('trim',$array)行(它从数组的每个元素中修剪空白)。你的爆炸分隔符是从后到前的。或者,应该读逗号空格,而不是逗号空格。尽管看起来OP的输入格式在历史中发生了变化。
foreach ( $items as $item ) {
echo "Doing something with '$item'...";
}
<?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>"