3 回答
![?](http://img1.sycdn.imooc.com/533e4c7b00013f3c02400205-100-100.jpg)
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";
}
![?](http://img1.sycdn.imooc.com/533e4cf4000151f602000200-100-100.jpg)
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与!==运算符一起使用。
![?](http://img1.sycdn.imooc.com/545863f50001df1702200220-100-100.jpg)
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变量来查找是否找到匹配项。
- 3 回答
- 0 关注
- 849 浏览
添加回答
举报