我有一个文本文件,其中包含以下内容:

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