分解并保留分隔符


Explode and leave delimiter

这是我的函数:

$words = explode('. ',$desc);
        $out = '';
        foreach ($words as $key => $value) {
            $out .= $value;
            $rand = rand(0, 4);
            if ($rand == 2) {
                $out .= "'n";
            } else {
                $out .= ' ';
            }
        }

简而言之,它是在随机点之后插入新行,但在这种情况下,点会被删除。

我怎么能做explode('. ',$desc),并在它们所在的地方留下点呢?

连接时只需将它们放回即可。

$words = explode('. ',$desc);
$out = '';
foreach ($words as $key => $value) {
    $out .= $value.'.';
    $rand = mt_rand(0, 4);
    if ($rand == 2) {
        $out .= "'n";
    } else {
        $out .= ' ';
    }
}

您还应该使用mt_rand(),它是rand()的更好版本,除非您喜欢而不是真正随机的结果。

不使用正则表达式主题的正面向后看。

$words = preg_split('/(?<='.)(?!'s*$)/', $desc);

在任何后面有dot的非字符处拆分。

试试这个代码。。

$words = explode('. ',$desc);
            $out = '';
            foreach ($words as $key => $value) {
                $out .= $value;
                $rand = rand(0, 4);
                if ($rand == 2) {
                   $out .= "<br>";
                } else {
                   $out .= ' ';
                }
            }