Pregunta

Tengo un archivo de texto con el siguiente contenido:

---> 12455  ---> 125  ---> KKK
---> 11366  ---> 120  ---> LLL
---> 12477  ---> 120  ---> YYY

Estoy usando el siguiente código PHP para buscar el archivo "---> 124" y obtengo los siguientes resultados:

---> 12455  ---> 125  ---> KKK
---> 12477  ---> 120  ---> YYY

Pero quiero que los resultados sean así:

---> 12455  
---> 12477  

Quiero que vuelva solo a la primera columna.

<?php
    $file = 'mytext.txt';
    $searchfor = '---> ' . "124";

    // the following line prevents the browser from parsing this as HTML.
    header('Content-Type: text/plain');

    // get the file contents, assuming the file to be readable (and exist)
    $contents = file_get_contents($file);

    // escape special characters in the query
    $pattern = preg_quote($searchfor, '/');

    // finalise the regular expression, matching the whole line
    $pattern = "/^.*$pattern.*\$/m";

    // search, and store all matching occurences in $matches
    if(preg_match_all($pattern, $contents, $matches)) {
        echo implode($matches[0]);
    } else {
        echo "No matches found";
    }
?>
¿Fue útil?

Solución

Cambia un poco tu enfoque. En lugar de almacenar el término de búsqueda y el separador en una sola cadena, use dos variables.

$sep = '--->';
$searchfor = '124';

$pattern = "/^$sep\s+($searchfor\d+)\s+.*/m";

// search, and store all matching occurences in $matches
if(preg_match_all($pattern, $contents, $matches)){
    echo implode(' ', $matches[1])."\n";
}

Salidas:

12455 12477

Manifestación.

Otros consejos

En primer lugar, separe sus preocupaciones:

  1. Leer el archivo
  2. Analizar el contenido
  3. Búsqueda

Usando iteradores, puede lograr algo genial aquí, pero necesitará una comprensión más profunda de la interfaz OOP y de la iteradora. Lo que recomendaré es un enfoque más simple:

<?php
//Read the file line by line
$handle = fopen('file.txt', 'r');
while(!foef($handle)){
    $content = fgets($handle);

    //Parse the line
    $content = explode('---> ', $content);

    //Analyse the line
    if($content[1] == 124){
        echo $content[0]."\n";
    }

}
fclose($handle);

Eso debería ser, solo adaptalo como lo ve, ¡no he probado el código aquí!

cambio "/^.*$pattern.*\$/m" a "/$pattern\d*/i"

y entonces echo implode($matches[0]); a foreach($matches[0] as $item) echo "$item<br />\r\n";

Si la estructura es siempre como ha demostrado, entonces:

  1. Lea el archivo Line by Line;
  2. explode(); cada línea por espacio  ;
  3. Leer el elemento [1] del resultado;

Esto me parece más lógico. Sin necesidad de regex aquí, porque funcionará más lento y luego simple explode operación.

Aquí hay un ejemplo:

$handle = fopen( 'file.txt', 'r' );
if ( $handle ) {
    while ( ( $line = fgets( $handle ) ) !== false ) {
        $matches = explode( ' ', $line );
        if ( $matches[4] == '124' )
            echo $matches[1] . '<br/>';
    }
}

prueba esto:

--->\s\d{5}

Regex es exagerado aquí, un simple explode('--->', $str) y seleccionar el primer elemento sería suficiente

$file = file_get_contents('file.txt');
$lines = explode('---> ', $file);
for($i=1; $i<count($lines); $i=$i+3)
if(strpos($lines[$i], '124')!==false)
    $col[$i/3] = /*'--> ' . */$lines[$i];
print_r($col);

Eso parece funcionar bien. Descopment el comentario anterior si desea -> incluido en la salida. Además, la matriz $ col resultante está indexada con el número de fila que se encuentra. Simplemente reemplace [$ I/3] con [] si no quiere eso.

Profundizando esto:

function SearchFileByColumn($contents, $col_num, $search, $col_count = 3) {
    $segs = explode('---> ', $contents);
    for($i=$col_num; $i<count($segs); $i=$i+$col_count)
        if(strpos($segs[$i], $search) !== false)
            $res[] = $segs[$i];
    return $res;
}

$results = SearchFileByColumn($contents, 1, '124');
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top