Reputation: 263
I get a variable which looks like this:
$var = "User list 1,,User list 3,User list 4,,,,User list 5,,,User list 6"
My question is how can I display that like below:
User list 1
User list 3
User list 4
User list 5
User list 6
I tried this: echo str_replace(",","<br>",$var);
but I get the wrong output:
User list 1
User list 3
User list 4
User list 5
User list 6
Any help? Thanks
Upvotes: 0
Views: 1093
Reputation: 1056
You can try this. First replace consecutive spaces with single space and then explode
on a single comma
and then implode
the array on <br>
tag to form the desired list as follows.
$string="User list 1,,User list 3,User list 4,,,,User list 5,,,User list 6";
$string = preg_replace("/,+/", ",", $string);
echo (implode('<br>',explode(',',$string)));
Upvotes: 2
Reputation: 21437
Simply use implode
and explode
along with array_filter
like as
$var = "User list 1,,User list 3,User list 4,,,,User list 5,,,User list 6";
echo implode("<br>",array_filter(explode(',',$var)));
Output :
User list 1
User list 3
User list 4
User list 5
User list 6
Edited :
Lets make it more clear stepwise
Step 1
We'll exploding string at ,
using explode
function of PHP like as
explode(',',$var);
which'll result into
Array
(
[0] => User list 1
[1] =>
[2] => User list 3
[3] => User list 4
[4] =>
[5] =>
[6] =>
[7] => User list 5
[8] =>
[9] =>
[10] => User list 6
)
Now we've empty values within array. So we need to remove that empty values using array_filter
like as
array_filter(explode(',',$var));
results into an array
Array
(
[0] => User list 1
[2] => User list 3
[3] => User list 4
[7] => User list 5
[10] => User list 6
)
Now as OP stated output must break at new line we'll simply use implode
along with <br>
like as
echo implode("<br>",array_filter(explode(',',$var)));
Results
User list 1
User list 3
User list 4
User list 5
User list 6
Explanation : Your attempt
echo str_replace(",","<br>",$var);
What you were doing over here is replacing each ,(comma)
along with <br>
which'll simply output your result.
Upvotes: 3
Reputation: 2530
You can use this
$var = "User list 1,,User list 3,User list 4,,,,User list 5,,,User list 6";
$arrvar = explode(',',$var);
$arrvar = array_values(array_filter($arrvar));
foreach($arrvar as $key=>$val)
{
echo $val."<br>";
}
Upvotes: 1
Reputation: 2482
You can make use of explode
$var = "User list 1,,User list 3,User list 4,,,,User list 5,,,User list 6";
$a = explode(',',$var);
foreach($a as $b=>$c)
{
if(!empty($c))
echo $c."<br>";
}
Upvotes: 1