Search code examples
phpstringstring-search

Search a file and migrate search term is in to 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?


Solution

  • $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);
    }