php - 在文本文件中搜索内容

时间:2013-12-02 20:43:22

标签: php

我有一个文本文件......内容如下

---> t11  ---> x1  ---> 
---> t22  ---> x2  ---> 
---> t33  ---> x3  ---> 
---> t24  ---> x2  ---> 
---> t35  ---> x3  ---> 
---> t46  ---> x4  ---> 

我如何只搜索第一列并返回在开头有t2的单词...任何帮助将不胜感激...我使用以下PHP代码...但它只返回一个单词与t2在开始时,我希望它在开始时用t2返回所有单词...

    <?php
$file = 'mytext.txt';
$searchfor = '---> t2';

// 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)){
    $strArray = explode('---> ',implode($matches[0]));


echo $strArray[1];

}
else{
   echo "No matches found";
}
?>

输出应该是......

---> t22
---> t24

2 个答案:

答案 0 :(得分:0)

您应该使用fgets()逐行检查文件,单独搜索每一行并显示您想要的任何内容。

while (!feof($stream)) {
    echo fgets($stream); //Display each line
}

但是,请考虑使用适当的查询功能迁移到数据库。

答案 1 :(得分:0)

<?php
$file = 'mytext.txt';
$searchfor = 't2';

header('Content-Type: text/plain');
$contents = file($file);
$matches = array();
foreach($contents as $lineNo => $line)
    if (substr(str_replace("---> ","",$line),0,strlen($searchfor)) === $searchfor)
        $matches[] = str_replace("---> ","",$line); // or use $matches[] = ++$lineNo . ': ' . $line;
if(count($matches))
    foreach($matches as $match)
        echo $match . "\n";
else
    echo "No matches found";
?>