3 回答

TA貢獻(xiàn)1866條經(jīng)驗(yàn) 獲得超5個(gè)贊
還有一個(gè)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";
}

TA貢獻(xiàn)1863條經(jīng)驗(yàn) 獲得超2個(gè)贊
像這樣做。這種方法可以讓你搜索一個(gè)任意大小的文件(大尺寸不會(huì)崩潰的腳本),并返回匹配的所有行你想要的字符串。
<?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與!==運(yùn)算符一起使用。

TA貢獻(xiàn)1788條經(jīng)驗(yàn) 獲得超4個(gè)贊
使用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;
}
在此文件上進(jìn)行測(cè)試時(shí):
foozah
barzah
abczah
它輸出:
富扎
更新:
如果未找到文本,則顯示文本,請(qǐng)使用類似以下內(nèi)容的方法:
<?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變量來查找是否找到匹配項(xiàng)。
- 3 回答
- 0 關(guān)注
- 864 瀏覽
添加回答
舉報(bào)