Search code examples
phpstring-search

Compare first word of each line of a file to a variable in php


I've just started php and I can't find an easy way to compare to a variable each first word of a line of a text file in a format("userid firstname lastname password").


Solution

  • <?php
         $mf = fopen("users.txt", "r") or die("Unable to open user database file!");
         $fc = file_get_contents('users.txt');
         $cv = "userid";
         if($fc == $cv) {
              //the contents of the file contain userid
         }
         fclose($mf);
    ?>
    

    This isn't exactly what you wanted, but it should steer you in the right direction. You will have to look into parsing the first word on each line and comparing it to a variable. Replace the if statement with the parsing.