使用PHP获取字符串的第n次出现的行号

时间:2018-06-27 20:07:15

标签: php regex

我有一个使用文本文件的Web应用程序,以实现某些类似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>

的行号

1 个答案:

答案 0 :(得分:0)

您可以逐行读取文件,并在每行中测试是否在第n次找到所需的字符串。一种方法是:

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);