为了账号安全,请及时绑定邮箱和手机立即绑定

PHP在txt文件中搜索并回显整行

PHP在txt文件中搜索并回显整行

PHP
哆啦的时光机 2019-10-10 14:28:24
我正在尝试使用php创建一个脚本,该脚本将在文本文件中搜索并获取整行并回显它。我有一个名为“ numorder.txt”的文本文件(.txt),并且在该文本文件中有几行数据,每5分钟会有新行出现(使用cron作业)。数据类似于:2 aullah17 name12 username我将如何创建一个php脚本来搜索数据“ aullah1”,然后抓起整行并回显它?(一旦回显,它应该显示“ 2 aullah1”(不带引号)。如果我没有清楚地解释任何事情和/或您想让我更详细地解释,请发表评论。
查看完整描述

3 回答

?
心有法竹

TA贡献1866条经验 获得超5个赞

还有一个PHP示例,将显示多行匹配:


<?php

$file = 'somefile.txt';

$searchfor = 'name';


// 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 "Found matches:\n";

   echo implode("\n", $matches[0]);

}

else{

   echo "No matches found";

}


查看完整回答
反对 回复 2019-10-10
?
小唯快跑啊

TA贡献1863条经验 获得超2个赞

像这样做。这种方法可以让你搜索一个任意大小的文件(大尺寸不会崩溃的脚本),并返回匹配的所有行你想要的字符串。


<?php

$searchthis = "mystring";

$matches = array();


$handle = @fopen("path/to/inputfile.txt", "r");

if ($handle)

{

    while (!feof($handle))

    {

        $buffer = fgets($handle);

        if(strpos($buffer, $searchthis) !== FALSE)

            $matches[] = $buffer;

    }

    fclose($handle);

}


//show results:

print_r($matches);

?>

注意,该方法strpos与!==运算符一起使用。


查看完整回答
反对 回复 2019-10-10
?
尚方宝剑之说

TA贡献1788条经验 获得超4个赞

使用file()和strpos():


<?php

// What to look for

$search = 'foo';

// Read from file

$lines = file('file.txt');

foreach($lines as $line)

{

  // Check if the line contains the string we're looking for, and print if it does

  if(strpos($line, $search) !== false)

    echo $line;

}

在此文件上进行测试时:


foozah 

barzah 

abczah


它输出:


富扎


更新:

如果未找到文本,则显示文本,请使用类似以下内容的方法:


<?php

$search = 'foo';

$lines = file('file.txt');

// Store true when the text is found

$found = false;

foreach($lines as $line)

{

  if(strpos($line, $search) !== false)

  {

    $found = true;

    echo $line;

  }

}

// If the text was not found, show a message

if(!$found)

{

  echo 'No match found';

}

在这里,我使用$found变量来查找是否找到匹配项。


查看完整回答
反对 回复 2019-10-10
  • 3 回答
  • 0 关注
  • 849 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信