PHP:将一个字符串分解为多行,并分别操作每一行


PHP: Breaking a string into multiple lines and manipulating each line separately

我从数据库中提取了一个字符串,它包含一些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行),这样我就可以为跨度设置"奇数"answers"偶数"类。

我该怎么做?

只需使用以PHP_EOL常量为分隔符的explode()函数:

$lines = explode(PHP_EOL, $original);

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

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

您可以用分隔符分解字符串,然后使用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++;
}

希望这能帮助

使用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;