PHP:将字符串分成多行并分别操作每一行

时间:2013-11-22 17:14:22

标签: php string-split

我从数据库中提取了一个字符串,其中包含一些html代码,例如:

something about thing one<br>
now comes the second thing<br>
we're not done yet, here's another one<br>
and last but not least is the fourth one<br>

所以我有四行,但是当我打印出字符串时,我得到一个输出,如上例所示。我想做的是操纵每一行,以便我能够做到这一点:

<span>something about thing one</span>
<span>now comes the second thing</span>
<span>we're not done yet, here's another one</span>
<span>and last but not least is the fourth one</span>

我还希望有一个计数器,表示字符串中有多少行(就像这一行有4行)所以我可以为span设置“odd”和“even”类。

我该怎么做?

3 个答案:

答案 0 :(得分:0)

只需使用explode()函数并将PHP_EOL常量作为分隔符:

$lines = explode(PHP_EOL, $original);

在您可以迭代返回的数组以解析行之后,例如:

foreach ( $lines as $line )
{
    echo '<span>'.$line.'</span>';
}

答案 1 :(得分:0)

使用explode进行拆分,我希望在这些方案中使用for循环而不是foreach,因为后者最后会返回一个空的span标记,因为它循环五次。

$arr    =   explode("<br>",$value);
for($i=0;$i<count($arr)-1; $i++){
echo "&lt;span&gt;".$arr[$i]."&lt;/span&gt;<br>";
}

要获得计数,您可以使用count功能:

echo count($arr)-1;

答案 2 :(得分:0)

您可以使用分隔符分解字符串,然后使用foreach循环来获得所需的答案。

$input = "omething about thing one<br>
now comes the second thing<br>
we're not done yet, here's another one<br>
and last but not least is the fourth one<br>";

//用br作为分隔符

分解输入字符串
  $data = explode ('<br>', $input );

//过滤$ data数组以删除任何空值或空值

$data   = array_filter($data);

//获取总数据

$count  = count($data);

//现在使用循环到你想要的东西

$i = 1;
foreach ( $data as $output) 
{
    //create class based on the loop
    $class = $i % 2 == 0 ? 'even' : 'odd';
    echo '<span class="'. $class .'">'. $output .'</span>';
    $i++;
}

希望这有帮助

相关问题