问题描述
例如,file example.txt 包含一些哈希值:
所以,我想PHP搜索1e9eea56686511e9052e6578b56ae018并打印出它的行号,在这个例子中是4.
请注意文件中不会有多个散列。
我在Internet上找到了一些代码,但是没有一个可以工作。 >
我试过这个:
<?PHP
$ string =1e9eea56686511e9052e6578b56ae018;
$ data = file_get_contents(example.txt);
$ data = explode(\\\
,$ data); $ $ b $ for($ line = 0; $ line< count($ data); $ line ++){
if(strpos($ data [$ line],$ string)> = 0){
die(String $ string line number:$ line);
}
}
?>
它只是说在第0行找到字符串....哪个不正确... 。
最后的应用程序比这个复杂得多...
在创建行号后,它应该替换其他字符串,并将更改保存到文件,然后进一步处理....
在此先感谢:)
pre $ code $ search =1e9eea56686511e9052e6578b56ae018;
$ lines = file('example.txt');
$ line_number = false;
while(list($ key,$ line)= each($ lines)and!$ line_number){
$ line_number =(strpos($ line,$ search)!== FALSE )? $ key + 1:$ line_number;
}
echo $ line_number;
一个内存保护程序版本,适用于较大的文件:
$ search =1e9eea56686511e9052e6578b56ae018;
$ line_number = false;
if($ handle = fopen(example.txt,r)){
$ count = 0; ($ line = fgets($ handle,4096))!== FALSE和!$ line_number){
$ count ++;
$ line_number =(strpos($ line,$ search)!== FALSE)? $ count:$ line_number;
}
fclose($ handle);
}
echo $ line_number;
I have an application which needs to open the file, then find string in it, and print a line number where is string found.
For example, file example.txt contains few hashes:
So, I want to PHP search for "1e9eea56686511e9052e6578b56ae018" and print out its line number, in this case 4.
Please note that there are will not be multiple hashes in file.
I found a few codes over Internet, but none seem to work.
I tried this one:
<?PHP
$string = "1e9eea56686511e9052e6578b56ae018";
$data = file_get_contents("example.txt");
$data = explode("\n", $data);
for ($line = 0; $line < count($data); $line++) {
if (strpos($data[$line], $string) >= 0) {
die("String $string found at line number: $line");
}
}
?>
It just says that string is found at line 0.... Which is not correct....
Final application is much more complex than that...After it founds line number, it should replace string which something else, and save changes to file, then goes further processing....
Thanks in advance :)
An ultra-basic solution could be:
$search = "1e9eea56686511e9052e6578b56ae018";
$lines = file('example.txt');
$line_number = false;
while (list($key, $line) = each($lines) and !$line_number) {
$line_number = (strpos($line, $search) !== FALSE) ? $key + 1 : $line_number;
}
echo $line_number;
A memory-saver version, for larger files:
$search = "1e9eea56686511e9052e6578b56ae018";
$line_number = false;
if ($handle = fopen("example.txt", "r")) {
$count = 0;
while (($line = fgets($handle, 4096)) !== FALSE and !$line_number) {
$count++;
$line_number = (strpos($line, $search) !== FALSE) ? $count : $line_number;
}
fclose($handle);
}
echo $line_number;
这篇关于PHP - 在文件中找到一个字符串,然后显示它的行号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!