转换/替换换行符

时间:2017-07-15 20:10:33

标签: php wordpress

我想替换Newline与我在Google上搜索但没有得到完美答案。

这是我的字符串

$string = 'multiple


newline



convert




or replace';

我正在使用

str_replace(PHP_EOL.PHP_EOL, PHP_EOL.' '.PHP_EOL, $string);

但输出:

multiple
 

newline
 

 
convert
 

 

or replace

结果应为:

multiple

 

newline

 

 

convert

 

 

 

or replace

任何人都可以帮忙解决这个问题...

1 个答案:

答案 0 :(得分:0)

我确定您的问题出在其他地方,但我的解决方案是preg_replace_callback

$string = 'multiple


newline



convert




or replace';
$r = preg_replace_callback(
    '/' . PHP_EOL . '(' . PHP_EOL . '+)' . PHP_EOL . '/',
    function($v) {
        return PHP_EOL .PHP_EOL . implode(PHP_EOL . PHP_EOL, array_fill(0, strlen($v[1]), ' ')) . PHP_EOL . PHP_EOL ;
    },
    $string
);

echo $r;
相关问题