需要的解决方案:
我正在使用一个简单的 PHP 脚本,它应该:
- 在文件第一行末尾添加“value4:::”
- 在所有下一行的末尾添加“:::”
我是编程新手,已经在这里坐了两天试图解决这个问题。可能是一个小细节,也可能是执行此任务的完全错误的方法。
这样做可能是错误的方法,或者可能是正则表达式问题?我真的不知道。
恳请您帮我解决问题。
信息:
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::::::
关于php - 为什么它在下一行的开头添加文本,而不是在右一行的末尾添加文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36911063/