Php 如何删除后跟空格的换行符?
我想删除所有的换行符,后面跟一个空格,或者换句话说;将所有以空格开头的行移到最后一行的末尾 例如:Php 如何删除后跟空格的换行符?,php,regex,preg-replace,str-replace,Php,Regex,Preg Replace,Str Replace,我想删除所有的换行符,后面跟一个空格,或者换句话说;将所有以空格开头的行移到最后一行的末尾 例如: $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
$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);
不是很优雅,但这应该可以
<?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]*)$
查找文件中匹配的所有内容。替换为连接在一起的第一个和第二个捕获组。使用以下正则表达式:
^([^\n]*)\n([^\n]*)$
查找文件中匹配的所有内容。替换为连接在一起的第一个和第二个捕获组。我想您需要编写一些代码。如果您逐行阅读,可以使用trim()函数。@henninghall-您的所有行都从上符号开始,以点结束?@tanjir可能会尝试使用它,但如果需要,更愿意使用正则表达式posible@henninghall所以很难创建正则表达式:(或者我太笨了:)我想您需要编写一些代码函数。@henninghall-您的所有行都从上符号开始,以点结束?@tanjir可能会尝试使用它,但如果需要,更愿意使用正则表达式posible@henninghall所以很难创建正则表达式:(或者我太笨了:)看起来不错,但在我的情况下因为某种原因不起作用。看起来不错,但在我的情况下因为某种原因不起作用。(人们可以经常使用\r
和\n
组合,而不是\r
,后者。)(人们可以经常使用\r
和\n
组合,而不是\r
,后者。)