我有一个使用文本文件的webapp,以实现一些类似CMS的功能。 但是,我想将单个文件用于多种类型的内容。 这是我的档案:
<!--TYPEA--><div>html content goes here</div>
<!--TYPEB--><div>some html content</div>
<!--TYPEA--><div>another line of html code</div>
<!--TYPEB--><div>random html</div>
<!--TYPEB--><div>something else</div>
<!--TYPEA--><div>still html</div>
...
我想使用php获取该行的行号,其中<--TYPEA-->
第n次出现(假设<!--TYPEA-->
在一行中不会多次出现)。
示例:$ n = 3和$ string =“ <!--TYPEA-->
”
结果:行号<!--TYPEA--><div>still html</div>
发布于 2018-08-14 14:01:02
你可以逐行读取文件,并在每一行上测试是否在第9次找到要查找的字符串。这样做的一种方法是:
function getLineNumber($n, $needle) {
$nCounter = 0; // will count the number of founds
$handle = fopen("cms.txt", "r");
if ($handle) {
$i = 0;
while (($line = fgets($handle)) !== false) {
// check for the needle
if (strpos($line, $needle) !== false) {
$nCounter++;
// if it is the nth found
if ($nCounter == $n) {
return $i;
}
}
$i++;
}
fclose($handle);
} else {
// error opening the file.
}
}
使用:
$n = 4;
$needle = '<!--TYPEA-->';
$lineNumber = getLineNumber($n, $needle);
https://stackoverflow.com/questions/-100002137
复制相似问题