2014-11-15 2 views
0

Как получить полную строку из позиции, полученной strpos()?PHP - Прочитать полную строку с позиции, strpos()

Вот мой код:

//$route_route sample: NAXOP UZ45 VIKIK 

$route_waypoint = explode(" ", $route_route); 
$file = "components/airways.txt"; 
$contents = file_get_contents($file); 

foreach ($route_waypoint as $waypoint) { 

    //$waypoint sample: NAXOP  
    $pos = strpos($contents, $waypoint); 

     if ($pos === false) { 

     continue; 

     } else { 

     $line = fgets($contents, $pos); // Here is my problem 

     //line sample: MES,W714,005,NAXOP,38.804139,30.546833,149,000, ,L 

     list($fix, $lat, $lon, $sample_data1, $sample_data2) = explode(',', $line); 

     echo "$fix, $lat, $lon";  

    } 

} 

Основная цель заключается в локализации «NAXOP», прочитать его полную строку, и эхо некоторые данные. Любая помощь приветствуется!

+0

Почему открыть файл для каждой итерации? –

+1

Прежде всего, вы должны вывести 'file_get_contents()' из цикла. То, как у вас там есть, вы загружаете файл на каждую итерацию цикла. – JakeParis

+0

уже удален, извините –

ответ

1

ОТКАЗ ОТ ОТВЕТСТВЕННОСТИ: если VIKIK подходит к NAXOP в $ contents. VIKIK Не будет найден, если есть несколько вхождений NAXOP || UZ45 || VIKIK, будет найдено только первое из каждого вхождения.

$len = strlen($contents); 
$pos = 0; 
foreach ($route_waypoint as $waypoint) { 
    $pos = strpos($contents, $waypoint, $pos); 
    if ($pos === false) { 
     continue; 
    } 
    else { 
     // Here is the critical section for matching the entire line: 

     // First look backwards from where $waypoint was found for the 
     // beginning of the line 
     $startOfLine = strrpos($contents, "\n", ($pos - $len)); 

     // Next look forwards from $waypoint to find the end of the line 
     $endOfLine = strpos($contents, "\n", $pos); 

     // we already have the file in memory, just read from that, 
     $line = substr($contents, $startOfLine, ($endOfLine - $startOfLine)); 

     list($fix, $lat, $lon, $sample_data1, $sample_data2) 
         = explode(',', trim($line)); 

     echo "$fix, $lat, $lon"; 

     // IDK if you want to match the same line twice or not. 
     $pos = $endOfLine; 
    } 
} 

Вот лучшая программа.

<?php 

$str = "NAXOP UZ45 VIKIK"; 
$regex = "/" . preg_replace("/ /", "|", $str) . "/"; 

$fp = fopen("test.dat", "r"); 

while ($line = fgets($fp)) { 
    if (preg_match($regex, $line)) { 
     echo $line; 
    } 
} 
fclose($fp); 

Вот test.dat

NAXOP 
UZ45 
VIKIK 
UZ45 VIKIK 
NAXOP 
SILLYSTRING 

Вот выход

NAXOP 
UZ45 
VIKIK 
UZ45 VIKIK 
NAXOP 
+0

Первый подход идеален, спасибо! –

0

Я использовал эту библиотеку в Су много программ .. проверить это я думаю, что это Решите точно, что у вас есть. Это работает точно так же, как она говорит ..

например

between ('@', '.', '[email protected]'); 
//returns 'online' 
//from the first occurrence of '@' 

ЦСИ: http://php.net/manual/en/function.substr.php

<?php 

    function after ($this, $inthat) 
    { 
     if (!is_bool(strpos($inthat, $this))) 
     return substr($inthat, strpos($inthat,$this)+strlen($this)); 
    }; 

    function after_last ($this, $inthat) 
    { 
     if (!is_bool(strrevpos($inthat, $this))) 
     return substr($inthat, strrevpos($inthat, $this)+strlen($this)); 
    }; 

    function before ($this, $inthat) 
    { 
     return substr($inthat, 0, strpos($inthat, $this)); 
    }; 

    function before_last ($this, $inthat) 
    { 
     return substr($inthat, 0, strrevpos($inthat, $this)); 
    }; 

    function between ($this, $that, $inthat) 
    { 
     return before ($that, after($this, $inthat)); 
    }; 

    function between_last ($this, $that, $inthat) 
    { 
    return after_last($this, before_last($that, $inthat)); 
    }; 

// use strrevpos function in case your php version does not include it 
function strrevpos($instr, $needle) 
{ 
    $rev_pos = strpos (strrev($instr), strrev($needle)); 
    if ($rev_pos===false) return false; 
    else return strlen($instr) - $rev_pos - strlen($needle); 
}; 
?> 
Смежные вопросы