php - 搜索字符串和返回行 PHP

标签 php line file-get-contents strpos

我正在尝试在 PHP 文件中搜索一个字符串,当找到该字符串时,我想返回该字符串所在的整个 LINE。这是我的示例代码。我在想我必须使用爆炸但无法弄清楚。

$searchterm =  $_GET['q'];

$homepage = file_get_contents('forms.php');

 if(strpos($homepage, "$searchterm") !== false)
 {
 echo "FOUND";

 //OUTPUT THE LINE

 }else{

 echo "NOTFOUND";
 }

最佳答案

只需使用 file 将整个文件读取为行数组功能。

function getLineWithString($fileName, $str) {
    $lines = file($fileName);
    foreach ($lines as $lineNumber => $line) {
        if (strpos($line, $str) !== false) {
            return $line;
        }
    }
    return -1;
}

关于php - 搜索字符串和返回行 PHP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9721952/

相关文章:

php - 使用 ffmpeg 上传视频截屏

c++ - SDL_RenderSetScale 和 SDL_RenderDrawLine 如何交互?

php - 将一百万条记录写入 Excel

php - 数据库中每件商品的价格历史记录

C 逐行读取文件

javascript - 如何在 Cordova 读取本地文本文件?

phpexplode() 将文本文件中的所有值存储到索引 [0]

php - YouTube V3搜索API PHP

PHP file_get_contents 很慢并返回 500 Internal Server Error

php - Twig - 尝试分割数组元素