我想要实现什么?
我想创建一个函数,可以在文本文件中搜索特定的单词。要搜索的单词由用户定义,必须以美元符号开头。
我的尝试
我在谷歌和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
)
$file
在你的 preg_match_all 中不包含文件内容。fopen
只返回一个文件句柄,可用于读取文件。 - Kylefile_get_contents
代替fopen
。 - benestar$fopen
应该改为fopen
。你从未检查文件是否真正打开。fopen
返回的值并不是文件的内容。你定义了函数findText
,但后来使用了findVariable
(不是同一个函数)。$matches
从未被正确定义。 - Sverri M. Olsen