2012-04-21 4 views
0

У меня есть текстовый файл, который я хочу читать, но исключить строки, содержащие определенный символ в начале (отсюда и «@», или что-то один определенный позже):PHP preg_match_all, прочитать содержание и исключить нежелательные

@ I don't want this line to be read 
This line should be read; 
"This one" should be read, too; 
'Also this one' should be read; 
...etc 
@ But this one should be ignored; 

В приведенном ниже коде я могу взорвать те, которые заканчиваются точкой с запятой («;»), но последняя строка не должна, потому что она начинается с «@».

$contents = file_get_contents($the_path); 
$result = array_map('trim', explode(";", $contents)); 

Любой намек на достижение этой цели? Благодарности

UPDATE коды:

// http://stackoverflow.com/questions/10257244/php-preg-match-all-read-content-and-exclude-unwanted/10257319 
    $results = array(); 
    $matches = array(); 
    $the_path = '/path/to/file.txt'; 
    if (is_file($the_path)) { 
    $contents = file_get_contents($the_path); 
    if ($contents) { 
     // ! array warning 
     // $contents = array_map('rtrim', $contents); 
     // $matches = preg_grep('#^@#', $contents, PREG_GREP_INVERT); 
     $matches = preg_split("/[\r\n]/", preg_replace("/@.*?[\r\n]/", "", $contents), NULL, PREG_SPLIT_NO_EMPTY); 

     if ($matches) { 
     foreach ($matches as $key => $val) { 
      $results[$key] = $val; 
     } 
     } 
    } 
    } 
    // Attempt to remove the first 0 key, and start from 1, because 0|value0 is considered NULL 
    $results = array_combine(range(1, count($results)), array_values($results)); 

    return !empty($results) ? $results : array(); 

UPDATE 2, работает должным образом с помощью DCoder:

$matches = array(); 
    if ($contents = file($the_path)) { 
     $contents = array_map('rtrim', $contents); 
     $keyword = '@'; 
     // Still output @line 
     // $matches = preg_grep('#^@#', $contents, PREG_GREP_INVERT); 
     // Ok, thanks to http://php.net/manual/de/function.preg-grep.php#85503 
     $matches = preg_grep("/{$keyword}/i", $contents, PREG_GREP_INVERT);   

     // $matches = preg_split("/[\r\n]/", preg_replace("/@.*?[\r\n]/", "", $contents), NULL, PREG_SPLIT_NO_EMPTY); 
     // dsm($matches); 
     if ($matches) { 
     foreach ($matches as $key => $match) { 
     $results[$key] = $match; 
     } 
     } 
    } 


    // $results = array_combine(range(1, count($results)), array_values($results)); 
    return $results; 
+0

просто используйте array_shift ($ results); для удаления первой записи –

+0

Спасибо. Он был опробован ранее, прежде чем закончил с этой уродливой линией – swan

+0

Спасибо, я всегда принимаю ответы, за исключением тех, у кого нет ответов :( – swan

ответ

1
// get the contents of the file as an array of lines 
$contents = file($the_path); 
if($contents === false) { 
    throw new Exception("Failed to open file {$the_path}"); 
} 
// drop ending newlines 
$contents = array_map('rtrim', $contents); 

// find all lines except those starting with @ 
$matched = preg_grep('#^@#', $contents, PREG_GREP_INVERT); 
+0

Спасибо, но все же получите предупреждение о массиве, возможно, в моем коде где-то. Предупреждение: array_map() [function.array-map]: Аргумент # 2 должен быть массивом – swan

+0

Убедитесь, что файл, который вы пытаетесь открыть, существует ('file' возвращает FALSE, если он не может его прочитать). – DCoder

+0

Да, с is_file ($ the_path), как обычно – swan

1

с этим кодом на $ линии будет содержать массив со всеми линии, которые не начинаются с @

$contents = file_get_contents($the_path); 
$lines = preg_split("/[\r\n]/", preg_replace("/@.*?[\r\n]/", "", $contents), null, PREG_SPLIT_NO_EMPTY); 
+0

Почти работает, за исключением того, что он добавляет пустые 0 | '' пары, которые не являются Ожидаемый – swan

+0

вы можете предоставить полные данные, для которых он не работает должным образом? –

+0

Обновляется по мере необходимости. Спасибо – swan

Смежные вопросы