如果第十个是特定单词,则从字符串中获取第一个和第三个单词

时间:2019-05-21 09:54:18

标签: php

我有一个不断更新的URL .txt文件,我想从第十个单词为“ B738”的每一行中获取第一个和第三个单词。这些单词带有':'

该文件中的示例为1行:(是的,为1行)

RYR98G:1374442:首末页:PI​​LOT :: 36.50552:-13.87929:31183:451:B738:438:LPFR:31000:LPMA:UK1:100:1:7010 :::: 1:I:0:0: 1:41:3:30:GCXO:+ VFPS + / V / PBN / A1B1C1D1S1S2 DOF / 190521 REG / EIEFF OPR / RYR PER / C RMK / TCAS:N0438F310 IXOL9V IXOLI DCT LATRU DCT VERAM Q205 PECKY UQ146 EPAKA EPAK1X :0:0 ::: 20190521084125:215:30.121:1020:

我想抓住“ RYR98G”和“ First Last”,因为第十个单词是B738

<?php


$text = file_get_contents('http://data.vattastic.com/vatsim-data.txt');
$lines = explode("\n", $text);
$skipped_content = implode("\n", array_slice($lines, 62));

echo nl2br($skipped_content);


?>

3 个答案:

答案 0 :(得分:3)

这样的事情应该做你想要的:

foreach ($lines as $line) {
    $words = explode(':', $line);
    if (isset($words[9]) && $words[9] == 'B738') {
        echo "First: $words[0]\nThird: $words[2]\n";
    }
}

输出(用于您的示例行):

First: RYR98G
Third: First Last

Demo on 3v4l.org

答案 1 :(得分:0)

<?php
$text = file_get_contents('http://data.vattastic.com/vatsim-data.txt');
$lines = explode(":", $text);
if( $lines[9] == "B738" ){
    echo $lines[0]; //RYR98G
    echo $lines[2]; //First Last
}
?>

答案 2 :(得分:0)

在这里,您需要将txt的内容加载到一个变量中。

<?php 
$input_lines = "RYR98G:1374442:First Last:PILOT::36.50552:-13.87929:31183:451:B738:438:LPFR:31000:LPMA:UK1:100:1:7010:::1:I:0:0:1:41:3:30:GCXO:+VFPS+/V/PBN/A1B1C1D1S1S2 DOF/190521 REG/EIEFF OPR/RYR PER/C RMK/TCAS:N0438F310 IXOL9V IXOLI DCT LATRU DCT VERAM Q205 PECKY UQ146 EPAKA EPAK1X:0:0:0:0:::20190521084125:215:30.121:1020:"; // example of line

$matches = array(); //Array 
$search = preg_match_all('/(.*?):(.*?)/im', $input_lines, $matches); //regex matching

if($matches[1][9] == "B738") //target :)
{
  print_r('B738 Found! <br />');
  print_r('Item 1!'.$matches[1][0].'<br />');
  print_r('Item 2!'.$matches[1][3].'<br />');
}

// Debug of your array. As you can see all items matched.
foreach ($matches[1] as $match) {
  echo " Item: ".$i."<br />";
    echo $match;
  $i++;

}