字符串替换不能正常工作Php

时间:2015-09-28 05:15:29

标签: php

我得到一个看起来像这样的变量:

$var = "User list 1,,User list 3,User list 4,,,,User list 5,,,User list 6"

我的问题是如何在下面显示:

User list 1
User list 3
User list 4
User list 5
User list 6

我试过了:echo str_replace(",","<br>",$var);

但我得错了输出:

    User list 1

    User list 3
    User list 4



    User list 5


    User list 6

有任何帮助吗?感谢

4 个答案:

答案 0 :(得分:3)

只需使用implodeexplode以及array_filter,如

$var = "User list 1,,User list 3,User list 4,,,,User list 5,,,User list 6";

echo implode("<br>",array_filter(explode(',',$var)));

输出

User list 1
User list 3
User list 4
User list 5
User list 6

已编辑:

让我们逐步明确

第1步

我们将使用PHP的,函数在explode处爆炸字符串,如

explode(',',$var);

将导致

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
)

现在我们在数组中清空了值。因此,我们需要使用array_filter删除空值,如

array_filter(explode(',',$var));

结果为数组

Array
(
    [0] => User list 1
    [2] => User list 3
    [3] => User list 4
    [7] => User list 5
    [10] => User list 6
)

现在OP声明输出必须在新行中断,我们只需使用implode<br>一样

echo implode("<br>",array_filter(explode(',',$var)));

结果

User list 1
User list 3
User list 4
User list 5
User list 6

Demo

说明: 你的尝试

echo str_replace(",","<br>",$var);

您在此处所做的就是将每个,(comma)<br>替换为简单输出结果。

答案 1 :(得分:2)

你可以试试这个。首先用单个空格替换连续的空格,然后explode上的single comma,然后implode <br> $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))); 上的数组,以形成所需的列表,如下所示。

display

答案 2 :(得分:1)

您可以使用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>";
}

答案 3 :(得分:1)

您可以使用此

        $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>";
        }