我想删除所有换行后跟空格或换句话说;将以空格开头的所有行移动到最后一行的末尾。
示例:
$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实现此目的?
答案 0 :(得分:2)
不是很优雅,但这应该有效。
<?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);
答案 1 :(得分:2)