搜索字符串和返回行 PHP
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9721952/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Search String and Return Line PHP
提问by Ninja Fist
I'm trying to search a PHP file for a string and when that string is found I want to return the whole LINE that the string is on. Here is my example code. I'm thinking I would have to use explode but cannot figure that out.
我正在尝试在 PHP 文件中搜索字符串,当找到该字符串时,我想返回该字符串所在的整个 LINE。这是我的示例代码。我想我将不得不使用爆炸但无法弄清楚。
$searchterm = $_GET['q'];
$homepage = file_get_contents('forms.php');
if(strpos($homepage, "$searchterm") !== false)
{
echo "FOUND";
//OUTPUT THE LINE
}else{
echo "NOTFOUND";
}
回答by martin
回答by Nugget
You can use fgets()
function to get the line number.
您可以使用fgets()
函数来获取行号。
Something like :
就像是 :
$handle = fopen("forms.php", "r");
$found = false;
if ($handle)
{
$countline = 0;
while (($buffer = fgets($handle, 4096)) !== false)
{
if (strpos($buffer, "$searchterm") !== false)
{
echo "Found on line " . $countline + 1 . "\n";
$found = true;
}
$countline++;
}
if (!$found)
echo "$searchterm not found\n";
fclose($handle);
}
If you still want to use file_get_contents()
, then do something like :
如果您仍想使用file_get_contents()
,请执行以下操作:
$homepage = file_get_contents("forms.php");
$exploded_page = explode("\n", $homepage);
$found = false;
for ($i = 0; $i < sizeof($exploded_page); ++$i)
{
if (strpos($buffer, "$searchterm") !== false)
{
echo "Found on line " . $countline + 1 . "\n";
$found = true;
}
}
if (!$found)
echo "$searchterm not found\n";
回答by JaredMcAteer
回答by Hasteur
You want to use the fgets function to pull an individual line out and then search for the
您想使用 fgets 函数拉出单独的一行,然后搜索
<?PHP
$searchterm = $_GET['q'];
$file_pointer = fopen('forms.php');
while ( ($homepage = fgets($file_pointer)) !== false)
{
if(strpos($homepage, $searchterm) !== false)
{
echo "FOUND";
//OUTPUT THE LINE
}else{
echo "NOTFOUND";
}
}
fclose($file_pointer)
回答by Thomas Bates
Here is an answered question about using regular expressions for your task.
这是有关在任务中使用正则表达式的已回答问题。
Get line number from preg_match_all()
Searching a file and returning the specified line numbers.
搜索文件并返回指定的行号。