第一次在这里发布,刚刚进入开发阶段。
试图用多行修改文本文件的输出,有些以字符开头,另一些以空白/制表符开头。我想让以tab/空白开始的行与它之前的任何行连接。我一直在研究用regex来实现这一点,但我不确定如何构建它。我想我需要使用"foreach"来查看每一行,找到每一行中的空白,并使用一系列regex将它们连接到前一行。这就是我已经走了多远,以及我认为前臂应该在哪里。
<?php
$file_handle = fopen("parse.txt", "r");
while (!feof($file_handle)){
$each_line = fgets($file_handle);
foreach ($each_line ){
}
print $each_line . "<br />";
}
fclose($file_handle);
?>
特定文本文件位于http://krondorkrew.com/parse/parse.txt如果你去那里查看/parse文件夹的索引,我也有这个php的当前版本。
我的下一步是通过在第一行爆炸将每一行分隔成单独的数组:在每一行中,但我仍然想在向你们这些了不起的人寻求帮助之前尝试自己解决这个问题(但如果你有任何见解,我不会把目光移开)
提前感谢您的帮助!
下面是一个缺少startsWithWhitespaceOrTab
函数的代码示例(它应该很容易编写,我将其作为示例)。剩下的已经起作用了:
foreach (file('parse.txt', FILE_IGNORE_NEW_LINES) as $line) {
if (!startsWithWhitespaceOrTab($line)) {
echo "'n";
}
echo $line;
}
请参阅PHP file
函数和foreach
循环。
此代码完成以下工作:
<?php
$output = "";
foreach (file('parse.txt') as $line) {
$output .= trim($line);
// if the current line starts noes not starts with a tab, we append
// a 'n to it
if (substr($line, 0, 1) != "'t") {
$output .= "'n";
}
}
echo $output;
但是您应该使用regexp进行这种文本操作。此处的代码板示例
使用file_get_contents()
将文件读取为单个字符串。然后,您可以使用regex来匹配空白,或者使用新行然后匹配空白,等等。
我会发布正则表达式,但我不确定你到底想做什么。你不能在这里测试正则表达式:http://gskinner.com/RegExr/
您可能想要以下内容:
<?php
$file_handle = fopen("parse.txt", "r");
$key = null;
$arr = array();
while (!feof($file_handle)){
$each_line = fgets($file_handle);
if ($key && preg_match('/^'s+/', $each_line)) {
$arr[$key] .= ' ' . trim($each_line);
} else if (preg_match('/^([a-zA-Z]+):(.*)$/', $each_line, $m)) {
$key = $m[1];
$arr[$key] = trim($m[2]);
}
}
fclose($file_handle);
?>
另一个解决方案。为您收集阵列中的行。不过我觉得我更喜欢@pinouchon的。
$file_handle = fopen("parse.txt", "r");
$fixed = array();
while (!feof($file_handle)){
$line = fgets($file_handle);
if (ctype_space($line[0])) { // Checks for whitespace
$fixed[count($fixed)-1].= trim($line); // Adds to previous line
} else {
$fixed[] = trim($line); // Otherwise, keep line as is
}
}
fclose($file_handle);
// Print
echo implode("'n",$fixed);