在PHP中从文本文件中获取用户的值

3

我想要实现什么?

我想创建一个函数,可以在文本文件中搜索特定的单词。要搜索的单词由用户定义,必须以美元符号开头。

我的尝试

我在谷歌和Stackoverflow上搜索了一下,但是没有找到相关教程。
所以我开始自己尝试:

function findText($userinput, $fileinput){
    $file = $fopen($fileinput, 'r');
    if(preg_match_all('/\$(\w){1,25}/g', $file, $matches_all)){
        if(strpos($matches_all, $userinput, $matches)){
            return $matches;
        }
    }
}

但好像它并没有起作用?

基本上

我想这样使用它

print_r(findVariable('myword', 'myfile.txt')); //print_r as it's an array

myfile.txt是:

$myword = also
$myword = and
$myword = this
Hello this is text to ignore
$op = po
Good day
$myword = none

然后它必须输出。
Array
(
    [0] => also
    [1] => and
    [2] => this
    [3] => none
)

1
$file 在你的 preg_match_all 中不包含文件内容。fopen 只返回一个文件句柄,可用于读取文件。 - Kyle
尝试使用file_get_contents代替fopen - benestar
$fopen 应该改为 fopen。你从未检查文件是否真正打开。fopen 返回的值并不是文件的内容。你定义了函数 findText,但后来使用了 findVariable(不是同一个函数)。$matches 从未被正确定义。 - Sverri M. Olsen
3个回答

2

使用preg_filter函数:

$data = file( $fileinput );    
print_r(preg_filter('#\$' . preg_quote($userinput, "#") . '\s*=\s*#', '', $data));

输出:

Array
(
    [0] => also
    [1] => and
    [2] => this
    [6] => none
)

1
使用file_get_contents收集文本文件数据。

e.g:

<?php
$filedata = file_get_contents("myfile.txt");
?>

你不需要使用 fopen 来完成这个操作


0
你可以在file的内容上使用preg_grep。但如果文件过大要小心。
$matches = preg_grep("/\$" . preg_quote($userinput, "/")
    . "/", file($fileInput));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接