如何删除换行符后跟空格?
How do I remove linebreaks followed by a whitespace?
我想删除所有换行符后跟一个空格或换句话说;将所有以空格开头的行移动到最后一行的末尾。
示例:
$str_before = "Lorem Ipsum is simply dummy text
of the printing and typesetting industry.
Lorem Ipsum has been the industry's
standard dummy text ever since the";
想要的结果:
$str_after = "Lorem Ipsum is simply dummy text of the printing and typesetting industry.
Lorem Ipsum has been the industry's
standard dummy text ever since the";
我已经试过了,但没有成功:
$str_after = str_replace("\n"." "," ", $str_before)
如何使用 php/regex 实现此目的?
不是很优雅,但应该可以。
<?php
$str = 'Lorem Ipsum is simply dummy text
of the printing and typesetting industry.
Lorem Ipsum has been the industry\'s
standard dummy text ever since the';
$newStr = []; $i = 0;
foreach(preg_split("/((\r?\n)|(\r\n?))/", $str) as $line) {
$i++;
if ($line[0] == chr(32)) {
$newStr[$i-1] .= $line;
} else {
$newStr[$i] = $line;
}
}
echo implode(PHP_EOL, $newStr);
使用以下正则表达式:
^([^\n]*)\n( [^\n]*)$
Demo here.
在文件中找到匹配的所有内容。替换为连接在一起的第一个和第二个捕获组。
我想删除所有换行符后跟一个空格或换句话说;将所有以空格开头的行移动到最后一行的末尾。
示例:
$str_before = "Lorem Ipsum is simply dummy text
of the printing and typesetting industry.
Lorem Ipsum has been the industry's
standard dummy text ever since the";
想要的结果:
$str_after = "Lorem Ipsum is simply dummy text of the printing and typesetting industry.
Lorem Ipsum has been the industry's
standard dummy text ever since the";
我已经试过了,但没有成功:
$str_after = str_replace("\n"." "," ", $str_before)
如何使用 php/regex 实现此目的?
不是很优雅,但应该可以。
<?php
$str = 'Lorem Ipsum is simply dummy text
of the printing and typesetting industry.
Lorem Ipsum has been the industry\'s
standard dummy text ever since the';
$newStr = []; $i = 0;
foreach(preg_split("/((\r?\n)|(\r\n?))/", $str) as $line) {
$i++;
if ($line[0] == chr(32)) {
$newStr[$i-1] .= $line;
} else {
$newStr[$i] = $line;
}
}
echo implode(PHP_EOL, $newStr);
使用以下正则表达式:
^([^\n]*)\n( [^\n]*)$
Demo here.
在文件中找到匹配的所有内容。替换为连接在一起的第一个和第二个捕获组。