我想创建一个搜索文本文件中特定单词的函数。要搜索的单词由用户定义,必须以美元开头。
我搜索过谷歌和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
)
答案 0 :(得分:2)
使用preg_filter:
$data = file( $fileinput );
print_r(preg_filter('#\$' . preg_quote($userinput, "#") . '\s*=\s*#', '', $data));
<强> OUTUT:强>
Array
(
[0] => also
[1] => and
[2] => this
[6] => none
)
答案 1 :(得分:1)
使用file_get_contents收集文本文件数据
e.g:
<?php
$filedata = file_get_contents("myfile.txt");
?>
您无需在此
中使用fopen答案 2 :(得分:0)