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

php-搜索文本文件中的内容,php,Php,我有一个文本文件。。。内容如下: ---> t11 ---> x1 ---> ---> t22 ---> x2 ---> ---> t33 ---> x3 ---> ---> t24 ---> x2 ---> ---> t35 ---> x3 ---> ---> t46 ---> x4 ---> 如何只搜索第一列并返回开头有t2的单词。。。任何帮助都将

我有一个文本文件。。。内容如下:

---> 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";
}
?>
您应该使用
fgets()
逐行检查文件,逐个搜索每一行,并显示您想要的内容,以防找到

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

但是,请考虑移动到具有适当查询能力的数据库。

<代码>
<?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";
?>

使用
fopen()
/
fgets()
而不是使用
file\u get\u contents()
来避免一次加载整个文件,如果你有一个相当大的文件,如果你有一个相当小的文件,使用
file()
而不是使用
file\u get\u contents()
。这将返回一个数组,数组中的每一行都包含在内。我认为您的
内爆()
分解()
已被交换。至少你在
'->'
上爆炸了,但我不知道这个字符串应该从哪里来。所以我猜你想用它来
内爆()
。我已经编辑了我的问题..哦,文件有120800行..@user2475714我编辑了我的答案,因为你已经编辑了你的OP问题。我再次尝试了你的代码,但没有找到匹配项。我想搜索第一列并返回所有开头有t2的单词
<?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";
?>