Hello,

Just got started using preg_grep, so I'm not sure exactly what I'm doing wrong here. I have an array of values I want to look for ($values). And I have a file that I'm opening via FTP ($file). I thought I'd do this with a foreach loop to go through each one of the $values and search the array of $file each time:

  foreach($value as $x) {
  $value_str = preg_grep("'/".$x."/'",$file);
  echo $x."<br>";
  }

This isn't returning anything though, and if I change the "'/".$x."/'" segment to "/Test Value/" it finds what I'm looking for in $file. I added the echo $x line to be sure the value was in the $value array, and it does show on the page.

Any assistance, or other suggestions on how to accomplish this would be appreciated!

    Realized I had some apostrophe's mixed up:

    "/'".$x."'/"

    Seems to be working better, just have to throw in some escape logic now for $x's where they have a "/" in them.

    Edit:
    Err.... Never mind that didn't quite work.

      I don't think you need to use a foreach loop on an array when dealing with preg_grep.
      For example:

      Example:

      $arrString = array('3E4', '3/21', '5T7', '4/91');
      $arr = preg_grep('#/#', $arrString);
      echo '<pre>'.print_r($arr,true);
      

      Output:

      Array
      (
          [1] => 3/21
          [3] => 4/91
      )
      

      preg_grep already travels through each array element and searches those values with the chosen pattern as its search criteria..

      I do question the logic of your snippet though.. because what you saying is the pattern is the value of the current array element, and if this value is found, echo it out.. so I'm not quite following what exactly you are looking for...

      Could you give some sample array values and what part of those values that preg_grep should be looking for?

        Sure, here are some examples. I have a database table with two rows: Green & Red. I'm parsing through text files and looking for the first line in the file that contains either Green or Red, then I want to include the entire line in a form to submit to the database.

        colors: Array ( [0] => Green [1] => Red )
        File Contents:
        Green Line
        Testing Value
        Black & White
        Nothing Good

        In this example, I'd like to identify the first line of the file as $file[0]=> Green Line.

        Does that help? Here's the full code, right now it's just echoing out stuff as I'm trying to figure out how I should go about this:

        <?php
        include 'connection.php';
        include 'header.inc.php';
        include 'connect_ftp.inc.php';
        
         $query_color = "select color,color_id from colors";
         $results_color = mysql_query($query_color) or die(mysql_error());
         while($row = mysql_fetch_array($results_color)){
         $color[] = $row['color'];
         sort($color);}
        
        // get contents of the current directory
        $contents = ftp_nlist($conn_id, $ftp_dir.$_GET['dir']);
        foreach ($contents as $v) {
         if (strpos($v, "test.txt") !== false) {
          $trimmed = substr($v,$ftp_dir_len);
          $file = array_map('rtrim',file('ftp://'.$ftp_user_name.':'.$ftp_user_pass.'@'.$ftp_server.'/'.$v));
          // search for green/red lines
          foreach($color as $x){
           $color_str = preg_grep("/".$x."/",$file);
           }
          echo "color_str: ";
          print_r($color_str);
          echo "<br>colors: ";
          print_r($color);
          echo "<br>File: ";
          foreach ($file as $w){
          echo "<br>".$w;
          }
         }}
        ?>
        

          Ok.. assume that there is a text file called somefile.txt, and it looked like this:

          somefile.txt

          Green Line
          Testing Value
          The Green Lantern
          Black & White
          Nothing Good
          Red Wine
          Yellow Stripes
          A fine red rose
          

          Could something like this be useful?

          $fileArray = file($_SERVER['DOCUMENT_ROOT'] . '/somefile.txt'); // change the path / filename to what you need...
          $arr_Green_Red = preg_grep('#(?:green|red)#i', $fileArray);
          
          if($arr_Green_Red){
          	foreach($arr_Green_Red as $val){
          		if(stripos($val, 'green') !== false){ // green detected
          			// insert $val into green table
          		} else if(stripos($val, 'red') !== false){ // red detected
          			// insert $val into red table
          		}
          	}
          }
          

            Well, sort of, but I can make the above query work if I just change:

              // search for green/red lines 
              foreach($color as $x){ 
               $color_str = preg_grep("/".$x."/",$file); 
               }
            

            to:

               $color_str = preg_grep("/Green|Red/",$file); 
            

            But that's not totally what I'm going for. The red/green example I stripped down so I could be sure the error wasn't in another section of my code. The basic problem is that I have two arrays, one from a text file, one from a database, and I need to find the corresponding rows in the text file from the values in the database. So, I need somehow for the first component of my preg_grep() to come from an array. My attempts at doing that are failing.

              Bumping for more ideas.

              More information on why I need that to process a variable is that the query that populates it will be dynamic, potentially contingent on the file name, etc. If I manually set $x = "/Green/" it works as well, just not if it loops through the foreach segment.

              Thanks in advance for the help!

                added some notes to your original code (and a little formatting, sorry, habit)

                <?php
                include 'connection.php';
                include 'header.inc.php';
                include 'connect_ftp.inc.php';
                
                $query_color = "select color,color_id from colors";
                // suggestion - for the purposes of the following code, I'd reccomend the query:
                $query_color = "SELECT DISTINCT( color ) FROM colors ORDER BY color ";
                // this will allow you to skip sorting the array, and only gets the relevant information, and prevents duplicates (also, your sorting of teh array is within the loop anyhows, so is sorting every iteration)
                $results_color = mysql_query($query_color) or die(mysql_error());
                while($row = mysql_fetch_array($results_color))
                {
                	$color[] = $row['color'];
                	sort($color);
                }
                
                // get contents of the current directory
                $contents = ftp_nlist($conn_id, $ftp_dir.$_GET['dir']);
                foreach ($contents as $v)
                {
                	if (strpos($v, "test.txt") !== false)
                	{
                		$trimmed = substr($v,$ftp_dir_len);
                		$file = array_map('rtrim',file('ftp://'.$ftp_user_name.':'.$ftp_user_pass.'@'.$ftp_server.'/'.$v));
                		// search for green/red lines
                		foreach($color as $x){
                			// adding sub array to color_str array, as if not, it will be overwritten each iteration
                			$color_str[$x] = preg_grep("/".$x."/",$file);
                		}
                		echo "color_str: ";
                		print_r($color_str);
                		echo "<br>colors: ";
                		print_r($color);
                		echo "<br>File: ";
                		foreach ($file as $w)
                		{
                			echo "<br>".$w;
                		}
                	}
                }
                ?> 

                  Aaaaah, that makes sense, now I see that I was overwriting the color_str[] each time. Huge help! I have no idea why I was sorting my array instead of a proper SQL statement - oops.

                  Thank you both!

                    Here's what I ended up doing for reference:

                    <?php
                    include 'connection.php';
                    include 'header.inc.php';
                    include 'connect_ftp.inc.php';
                    
                    $query_color = "select distinct(color),color_id from colors order by color";
                    $results_color = mysql_query($query_color) or die(mysql_error());
                    while($row = mysql_fetch_array($results_color)){
                    	$color[] = $row['color'];
                    }
                    
                    // get contents of the current directory
                    $contents = ftp_nlist($conn_id, $ftp_dir.$_GET['dir']);
                    foreach ($contents as $v) {
                    	if (strpos($v, "test.txt") !== false) {
                    		$file = array_map('rtrim',file('ftp://'.$ftp_user_name.':'.$ftp_user_pass.'@'.$ftp_server.'/'.$v));
                    		// search for different aspects of the file
                    		foreach($color as $v){
                    			if (is_numeric(key(preg_grep('/'.$v.'/',$file)))){
                    			$color_str[$v] = preg_grep('/'.$v.'/',$file);
                    			}
                    		}
                    	}
                    }
                    echo "<pre>color_str: ".print_r($color_str,true);
                    echo "colors: ".print_r($color,true);
                    echo "File Contents: ".print_r($file,true);
                    ?>
                    

                    Which produces this:

                    color_str: Array
                    (
                        [Green] => Array
                            (
                                [0] => Green Line
                                [4] => Green take two
                            )
                    
                    )
                    colors: Array
                    (
                        [0] => Green
                        [1] => Red
                    )
                    File Contents: Array
                    (
                        [0] => Green Line
                        [1] => Testing Value
                        [2] => Black & White
                        [3] => Nothing Good
                        [4] => Green take two
                    )
                    
                      Write a Reply...