如何在读取文件时修复行格式

时间:2014-09-12 06:42:39

标签: php regex

我如何修复最后一行,使它们看起来像前两个正则表达式?

"XY30-0601" "LMF II Trump"  7
"ZR3-0003601"   "Durable canvas"    3

"GQ450-020061"  "DMZ Power
Epic
Durable canvas
Handle for easy transport
Sturdy buttons to keep the case rolled up
Reinforced case stitching
"   17

我期待

"XY30-0601" "LMF II Trump"  7
"ZR3-0003601"   "Durable canvas"    3
"GQ450-020061"  "DMZ Power Epic Durable canvas Handle for easy transport Sturdy buttons to keep the case rolled up Reinforced case stitching"   17

2 个答案:

答案 0 :(得分:3)

试试下面的正则表达式,并用空格替换匹配的换行符。

\n(?:(?!")|(?=" +\d+))

DEMO

<强>代码:

<?php
$string = <<<EOT
"XY30-0601" "LMF II Trump"  7
"ZR3-0003601"   "Durable canvas"    3

"GQ450-020061"  "DMZ Power
Epic
Durable canvas
Handle for easy transport
Sturdy buttons to keep the case rolled up
Reinforced case stitching
"   17
EOT;
$pattern = '~\n(?:(?!")|(?=" +\d+))~';
$replacement = " ";
echo preg_replace($pattern, $replacement, $string);
?>

<强>输出:

"XY30-0601" "LMF II Trump"  7
"ZR3-0003601"   "Durable canvas"    3
"GQ450-020061"  "DMZ Power Epic Durable canvas Handle for easy transport Sturdy buttons to keep the case rolled up Reinforced case stitching "   17

答案 1 :(得分:0)

(?=[^"]*")\n

你可以space使用this.replace。它使用正向前瞻来查找\n之前的"

参见演示。

http://regex101.com/r/hQ1rP0/14