php - 为什么它在下一行的开头添加文本,而不是在右一行的末尾添加文本?

标签 php regex flat-file

需要的解决方案:

我正在使用一个简单的 PHP 脚本,它应该:

  1. 在文件第一行末尾添加“value4:::”
  2. 在所有下一行的末尾添加“:::”

我是编程新手,已经在这里坐了两天试图解决这个问题。可能是一个小细节,也可能是执行此任务的完全错误的方法。

这样做可能是错误的方法,或者可能是正则表达式问题?我真的不知道。

恳请您帮我解决问题。


信息:

newstest.db 文件如下所示:

ID:::value1:::value2:::value3:::
1:::My:::first:::line:::
2:::My:::second:::line:::
3:::Your:::third:::line:::

使用这个 php 脚本我想让它看起来像这样:

ID:::value1:::value2:::value3:::value4:::
1:::My:::first:::line::::::
2:::My:::second:::line::::::
3:::Your:::third:::line::::::

问题:

到目前为止我几乎已经明白了,但我很困惑为什么它会在 second 行的 beginning 中添加“value4::::”,然后在所有其余行的开头(不是结尾)添加“:::”。

所以我得到一个看起来像这样的文件:

ID:::value1:::value2:::value3:::
value4:::1:::My:::first:::line:::
:::2:::My:::second:::line:::
:::3:::Your:::third:::line:::

我认为:

$lineshere = 'Some text here:::';    
$lines1 = $linehere.'value4:::';

会输出“这里有一些文本:::value4:::”

问题可能是由于这种逐行添加的方式造成的吗?

$lines = '';
$lines.= 'My test';
$lines.= ' is here';
echo $lines;

我是编程新手,所以我可能使用了完全错误的函数 tec 来完成这项工作。

但在这种情况下,它会在错误的位置添加空格或换行符/换行符。


我对这个解决方案的尝试:

<?php
// specify the file
$file_source="newstest.db";

// get the content of the file
$newscontent = file($file_source, true);

//set a start value (clear memory)
$lines ='';

// get each line and treat it line by line. 

foreach ($newscontent as $line_num => $linehere) {  

    // add "value4:::" at the end of FIRST line only, and put it in memory $lines 
    if($line_num==0) {
        $lines.= $linehere.'value4:::';

        // Just to see what the line looks like
        //echo 'First line: '.$lines.'<br /><br />';
    }

    // then add ":::" to the other lines and add them to memory $lines
    if($line_num>0) {
        $lines1 = $linehere.':::';
        $lines.= $lines1;

        //just look at the line
        //echo 'Line #'.$line_num.': '.$lines1.'<br /><br />';
    }
}

//Write new content to $file_source
$f = fopen($file_source, 'w');
fwrite($f,$lines);
fclose($f);

echo "// to show the results ar array<br /><br />";

$newscontentlook = file($file_source, true);
print_r(array_values($newscontentlook));
?>

最佳答案

这实际上很容易用 file_get_contents 实现和 preg_replace ,即:

$content = file_get_contents("newstest.db");
$content = preg_replace('/(^ID:.*\S)/im', '$1value4:::', $content);
$content = preg_replace('/(^\d+.*\S)/im', '$1:::', $content);
file_put_contents("newstest.db", $content);

输出:

ID:::value1:::value2:::value3:::value4:::
1:::My:::first:::line::::::
2:::My:::second:::line::::::
3:::Your:::third:::line::::::

Ideone Demo

关于php - 为什么它在下一行的开头添加文本,而不是在右一行的末尾添加文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36911063/

相关文章:

c++ - 没有匹配函数调用 ‘regex_search(...)'

java - 重复字符串替换

google-app-engine - 使用 Google Cloud Dataflow 合并平面文件并导入 Cloud SQL

ssis - 行分隔符不能与列分隔符相同

php - 在非对象日期格式上调用成员函数 format()

php - Laravel 4 中的包 Controller

regex - 如何使用正则表达式分隔字符串中的数字和字符,如 "30M1000N20M"

database - NHibernate 可以持久保存到平面文件而不是数据库吗?

php - 手动创建一个空的 PDO 记录集

php - 如何设置批处理文件来获取txt文件并将一些数据放入mySQL数据库中