Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to find words from a text file using PHP

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 122
    Comment on it

    Hi if you have a long text file full of line and you need to search some text in it then you can use this function. This function will accept the words from user then search from a text file and return the lines which have matching words.

    <?php
    $SearchThisFile = 'mystudentfiles.txt';
    $LookForMatch = 'student_city'; 
    header('Content-Type: text/plain');
    
    // get the file contents, assuming the file to be readable (and exist)
    $contents = file_get_contents($SearchThisFile);
    // escape special characters in the query
    $pattern = preg_quote($LookForMatch, '/');
    // finalise the regular expression, matching the whole line
    $pattern = "/^.*$pattern.*\$/m";
    // search, and store all matching occurences in $WordDetect
    if(preg_match_all($WordsInMatch $contents, $WordDetect)){
       echo "Found matches:\n";
       echo implode("\n", $WordDetect[0]);
    }
    else{
       echo "No matches found";
    }
    

    This function use the $LookForMatch key as param by user and $SearchThisFile as text file. When the matches contents found the pattern in any line, it will print the line to the user.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: