質問

次の内容を含むテキストファイルがあります。

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

次のPHPコードを使用して「---> 124」のファイルを検索しています。次の結果が得られます。

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

しかし、私は結果を次のようにしたいです:

---> 12455  
---> 12477  

最初の列のみを返してほしい。

<?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";
    }
?>
役に立ちましたか?

解決

あなたのアプローチを少し変えてください。検索用語とセパレーターを単一の文字列に保存する代わりに、2つの変数を使用します。

$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";
}

出力:

12455 12477

デモ。

他のヒント

まず第一に、あなたの懸念を分離します:

  1. ファイルを読んでください
  2. コンテンツを解析します
  3. 探す

ここでは、イテレーターを使用すると、素晴らしいことを実現できますが、OOPとIteratorインターフェイスをより深く理解する必要があります。私がお勧めするのは、より簡単なアプローチです:

<?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);

それはそれでなければなりません、あなたがそれを見るようにそれを調整するだけで、私はここでコードをテストしていません!

変化する "/^.*$pattern.*\$/m""/$pattern\d*/i"

その後 echo implode($matches[0]);foreach($matches[0] as $item) echo "$item<br />\r\n";

構造が常に示されている通りである場合、次のとおりです。

  1. 行ごとにファイルを読んでください。
  2. explode(); 各線で宇宙  ;
  3. 要素を読んでください [1] 結果の;

これは私にとって最も論理的なようです。必要ありません regex ここでは、それはより遅く動作するのでシンプルに動作するので explode 手術。

これが例です:

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

これを試して:

--->\s\d{5}

正規表現はここでは過剰で、簡単です explode('--->', $str) そして、最初の要素を選択するだけで十分です

$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);

それはうまくいくようです。あなたが - >を出力に含める必要がある場合、上記のコメントを解除します。また、結果の$ colアレイは、見つかった行番号でインデックス付けされます。 [$ i/3]を[]が必要ない場合は[]に置き換えるだけです。

これを促進する:

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');
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top