简体   繁体   English

转换/替换换行符为

[英]Convert / replace newline to  

I want to replace Newline with &nbsp I am searching on google but not get perfect answer. 我想用在Google上搜索的&nbsp替换换行符,但没有完美的答案。

This is my string 这是我的弦

$string = 'multiple


newline



convert




or replace';

I am using 我在用

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

but output: 但输出:

multiple
 

newline
 

 
convert
 

 

or replace

The result should be: 结果应为:

multiple

 

newline

 

 

convert

 

 

 

or replace

Any one help please to solve this problem... 任何人的帮助请解决这个问题...

I'm sure that your problem is somewhere else, but here's my solution, using preg_replace_callback : 我确定您的问题在其他地方,但这是我的解决方案,使用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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM