搜索文件并将搜索词迁移到新文件中

发布于 2024-10-02 06:57:35 字数 793 浏览 1 评论 0原文

此代码可以创建一个新的 .txt 文件,如果该文件尚不存在,它将创建该文件。

<?php
$file = 'people.txt';
// Open the file to get existing content
$current = file_get_contents($file);
// Append a new person to the file
$current .= "John Smith\n";
// Write the contents back to the file
file_put_contents($file, $current);
?>

这里的代码将每一行字符串标识为一个标记。

<?php
$string = "This is\tan example\nstring";
/* Use tab and newline as tokenizing characters as well  */
$tok = strtok($string, " \n\t");

while ($tok !== false) {
    echo "Word=$tok<br />";
    $tok = strtok(" \n\t");
}
?>

people.txt 看起来像这样

John Smith
John Meyer
John Chase 
John Smith    //i want to transfer this set of string into a new file

我在这里缺少什么?

This code enables to create a new .txt file, if the file doesn't exist yet, it will create the file.

<?php
$file = 'people.txt';
// Open the file to get existing content
$current = file_get_contents($file);
// Append a new person to the file
$current .= "John Smith\n";
// Write the contents back to the file
file_put_contents($file, $current);
?>

And this code here identifies each line of string into a token.

<?php
$string = "This is\tan example\nstring";
/* Use tab and newline as tokenizing characters as well  */
$tok = strtok($string, " \n\t");

while ($tok !== false) {
    echo "Word=$tok<br />";
    $tok = strtok(" \n\t");
}
?>

The people.txt looks like this

John Smith
John Meyer
John Chase 
John Smith    //i want to transfer this set of string into a new file

What am i missing here?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

请止步禁区 2024-10-09 06:57:35
$searchTerm = 'John Smith';
$file = 'people.txt';
$fileFound = 'peopleFound.txt';
$current = file_get_contents($file);
if (strpos($searchTerm, $current) !== false) {
    file_put_contents($fileFound, $searchTerm."\n", FILE_APPEND);
}
$searchTerm = 'John Smith';
$file = 'people.txt';
$fileFound = 'peopleFound.txt';
$current = file_get_contents($file);
if (strpos($searchTerm, $current) !== false) {
    file_put_contents($fileFound, $searchTerm."\n", FILE_APPEND);
}
笑咖 2024-10-09 06:57:35
$fp=fopen('people.txt','a+');
fputs($fp,"John Smith\r\n");
fclose($fp);

打开并附加文件,不要将其全部读入并附加到后面并将其全部写回。当文件超过一定大小时,效率就会很低。我不确定你是如何尝试标记它的。在我看来,你可以做一个 $names=file('people.txt'); 并立即将它们放入数组中......

$fp=fopen('people.txt','a+');
fputs($fp,"John Smith\r\n");
fclose($fp);

open and append the file, don't read it all in and append to the back and write it all back out. when the file gets past a certain size that will be real inefficient. I'm not sure how it is you're trying to tokenize it. seems to me you could just do a $names=file('people.txt'); and have them in an array immediately...

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文