PHP explode()内置函数没有像我预期的那样工作


PHP explode() built-in function not working as I expected

我尝试了PHP explod()内置函数来解释存储在mysql数据库中的文本数据
这是我尝试过的PHP代码示例:

// Get mysql database data(with 'n).
$str_in = 
'one
two
three
fore
five
six
';
// Convert 'n into <br>.
$str = nl2br($str_in);
// Explode $str and wrapped into <p> tags.
$str_exploded = explode("<br><br>",$str);
foreach($str_exploded as $sub_str) {
    echo '<p>'.$sub_str.'</p>';
}

然后我得到了这个输出。

<p>one<br>
two<br>
three<br>
<br>
fore<br>
five<br>
<br>
six<br>
</p>

但这不是我所期望的。我想要这样的东西。

<p>one<br>
two<br>
three</p>
<p>fore<br>
five</p>
<p>six</p>

我怎样才能做到这一点?谢谢


是行上唯一的东西时,您要做的是删除它。

Strreplace应该使用参数"
"answers""的替换

您错误地认为nl2br函数将"''n"替换为<br>。实际上,它在'n之前插入<br />。因此,'n'n变为<br />'n<br />'n。您的

explode("<br><br>",$str)

没有按预期工作。

为了修复它,我使用了'n'n:爆炸

代码

<?php
$str_in =
'one
two
three
fore
five
six
';
$str_exploded = preg_split("/(:?'r?'n){2}/",$str_in);
$n = count($str_exploded);
for ($i = 0; $i < $n; ++$i)
{
    // Convert 'n into <br>.
    $str_exploded[$i] = nl2br($str_exploded[$i]);
    echo '<p>'.$str_exploded[$i]."</p>";
    if ($i !== $n - 1)
    {
        print "'n'n";
    }
}

输出

<p>one<br />
two<br />
three</p>
<p>fore<br />
five</p>
<p>six<br />
</p>