문제

다음 내용이있는 텍스트 파일이 있습니다.

---> 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";
    }
?>
도움이 되었습니까?

해결책

접근 방식을 조금 변경하십시오. 검색어와 분리기를 단일 문자열로 저장하는 대신 두 변수를 사용하십시오.

$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와 반복자 인터페이스에 대한 더 깊은 이해가 필요합니다. 내가 추천하는 것은 더 간단한 접근법입니다.

<?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}

Regex는 여기에서 과잉입니다 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