Search code examples
phpregexfilterfile-read

How to filter out letters from text file (start of string and end) , then print them out


The function needs to skip the lines in text file (after reading it) with contains symbol or numbers in FIRST && LAST string position. For example string($password column) 121dafasd should be skipped AND not printed out, because it starts with number I have tried many things, but all trials failed. Im new to PHP language

THE CODE
 function dataPrint(){

  print "\t"." Users: Login Password  <br>";
 $file=fopen("data.txt" , "c");
 if (!$file)
 print "Error! No such file!";

else {                                                    
 print "<table><tr><th width=\"50%\">Login</th>
 <th width=\"50%\">Password</th>
 ";
             $info=file("data.txt");

         foreach($info as $rec)
         {

                 $rec=rtrim($rec);

                 print("<tr>");
                 list($login, $pass) = explode(' ', "$rec");
                 print("<td>$login</td>");
                 print("<td>$pass</td>");

         }

   print("</table>");

Right now it prints all data as table

Login   Password 
quartz  2sp1lzod54at3sia6
quartz1 73u168rtz54a2q
quartz2 odsp@aw1rs

But it should print only those lines with contains only letters in start && end of string

Example :
Login     Password
quartz1   1asdfasdfdf@a   <----- NOT VALID(Should not be printed)
quartz2   asdf!2adf1      <----- NOT VALID(Should not be printed)
quartz3   asdf211@11a     <----- VALID
quartz4   gsasdff11e      <----- VALID
quartz5   fd@adf!adf1d    <----- VALID

The end should look like this..

Login     Password
quartz3   asdf211@11a   
quartz4   gsasdff11e     
quartz5   fd@adf!adf1d     

Solution

  • You can use preg_match to verify that your passwords start and end with a letter:

    foreach($info as $rec) {
        $rec=rtrim($rec);
        list($login, $pass) = explode(' ', "$rec");
        if (preg_match('/^[a-z].*[a-z]$/i', $pass)) {
            print("<tr>");
            print("<td>$login</td>");
            print("<td>$pass</td>");
            print("</tr>\n");
        }
    }
    

    Output:

    <tr><td>quartz3</td><td>asdf211@11a</td></tr>
    <tr><td>quartz4</td><td>gsasdff11e</td></tr>
    <tr><td>quartz5</td><td>fd@adf!adf1d</td></tr>
    

    Demo on 3v4l.org