I have a string like this:
$d = 'game, story, animation, video';
And I want to change it to a result like this:
<a href="game">game</a>, <a href="story">story</a>, <a href="animation">animation</a>, <a href="video">video</a>
So I think I have to split $d by ',' then use a for
loop.
I have tried this:
$d = 'game, story, animation, video';
list($a, $b, $c, $d) = explode(" ,", $d);
But how do I split it if I don't know how many ',' are going to be there, and reach the desired result?
There are many ways this could be accomplished here is one. by using a foreach
loop you should be able to accomplish what you are attempting to do.
You also need to assign you array items correctly, by casting as a string and using the [ ]
shorthand or using array()
$d = "game, story, animation, video";
$out = '' ;
foreach(explode(",",$d) as $item){
$out .= "<a href='$item' />$item</a>";
}
echo $out;
and if you need the ,
between you could use this
$d = "game, story, animation, video";
$out = [] ;
foreach(explode(",",$d) as $item){
$out []= "<a href='$item' />$item</a>";
}
echo implode(",",$out);
read more here
The key here is to realise that you can break this line into two parts:
list($a, $b, $c, $d) = explode(" ,", $d);
First, it takes the string $d
and splits it into an array, let's call it $items
:
$items = explode(" ,", $d);
Then the list()
construct takes the items from that array and puts them into separate named variables:
list($a, $b, $c, $d) = $items;
If you don't know how many items are going to be in the list, you can just skip the second step, and work with the array, probably using a foreach
loop:
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);
Or:
$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);
Output for each:
string(112) "<a href="game">game</a>, <a href="story">story</a>, <a href="animation">animation</a>, <a href="video">video</a>"