0

我想问一个与上一个问题稍有不同的问题(从字符串中删除新行):

我想从字符串中删除新行,除非在新行上的文本之前有一个空格“   ”(这表明这是一个新段落。这是一个例子:

   This is the first bit of text. It continues for a while until
there is a line break. It then continues for a bit longer but 
the line break also continues alongside it. 
   What you see here is the second paragraph. You'll notice that 
there is a space to mark the beginning of the paragraph. However
When joining these lines, a computer may not realize that the next
paragraph exists in this way. 
4

3 回答 3

3
$result = preg_replace('/\n++(?! )/', ' ', $subject);

正是这样做的。

解释:

\n++  # Match one or more newlines; don't backtrack
(?! ) # only if it's impossible to match a space afterwards
于 2013-09-15T14:56:35.270 回答
0

通过 end-line char 分解文本(使用 PHP_EOL 常量)并使用trim

$lines = explode(PHP_EOL,$text);
$lines = array_map(function($line){
    return trim($line);
},$lines);
$text = implode(PHP_EOL,$lines);

// or if you are not familiar w/ array_map, simple use foreach
$lines = array();
foreach(explode(PHP_EOL,$text) as $line)
     $lines[] = trim($line);
$text = implode(PHP_EOL,$lines);
于 2013-09-15T14:58:23.027 回答
0

看起来像您的文件中嵌入的小端 BOM。

在没有它们的情况下,它们必须被删除或重写文件。

您可以使用像这样的正则表达式将它们剥离出来\xFF\xFE

这是您在十六进制编辑器中的部分文本。

 00 61 00 6C 00 6F 00 6E 00 67 00 73 00 69 00 64 
 00 65 00 20 00 69 00 74 00 2E 00 20 00 0D 00 20 
 00 FF FE 20 00 FF FE 20 00 FF FE 57 00 68 00 61 
 00 74 00 20 00 79 00 6F 00 75 00 


 alongside it. 
    What you
于 2013-09-15T20:04:23.803 回答