Help running PHP function on 1st word in a Pipe Delimited CSV file

Discussion in 'PHP' started by scriptglue, Sep 26, 2008.

  1. #1
    I have a csv file that I want to run some php code on the first word in each line and add the result to the end of the line /save and repeat the process for all lines in the words.csv

    Example Line with fat cat being the first word:
    fat cat|black|2

    words.csv
    cat|black|2
    dog|brown|3s
    hot|cold|warm
    mon|tues|weds

    words.csv after running code for each
    cat|black|2|result blah
    dog|brown|3s|blah blah
    hot|cold|warm|hello blah
    mon|tues|weds|blah result blah
     
    scriptglue, Sep 26, 2008 IP
  2. themole

    themole Peon

    Messages:
    82
    Likes Received:
    7
    Best Answers:
    0
    Trophy Points:
    0
    #2
    Not sure I quite understand what you're asking for, but this should get you going in the right direction:

    
    
    $contents = file_get_contents('location/to/file.txt');
    
    $contents = explode("\n", $contents); //may need to use \r instead of \n
    
    $new_contents = '';
    foreach($contents as $line)
    {
    	$new_contents .= "$line|result blah";
    }
    
    Code (markup):
     
    themole, Sep 27, 2008 IP
  3. LogicFlux

    LogicFlux Peon

    Messages:
    2,925
    Likes Received:
    102
    Best Answers:
    0
    Trophy Points:
    0
    #3
    
    
    foreach($contents as $line)
    {
      $lineParts = array_map('trim', explode('|', $line));
    
      preg_match('#\s*(\w+)( *.*)#', $lineParts[0], $matches);
    
      $new_contents .= ;// create new line here
    
    }
    
    PHP:
    Now $lineParts is the contents of each "column" in an array. $matches[1] is the first word in the first column and $matches[2] is everything after the first word, which could be empty.
    Use these variables to reassemble the line as you wish.

    If you want to save the results use fopen and fwrite to write the new results to the file.
     
    LogicFlux, Sep 28, 2008 IP