首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何使用php获取字符串第n次出现的行数?

如何使用php获取字符串第n次出现的行数?
EN

Stack Overflow用户
提问于 2018-08-14 04:49:39
回答 1查看 0关注 0票数 0

我有一个使用文本文件的webapp,以实现一些类似CMS的功能。 但是,我想将单个文件用于多种类型的内容。 这是我的档案:

代码语言:javascript
复制
<!--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>

EN

回答 1

Stack Overflow用户

发布于 2018-08-14 14:01:02

你可以逐行读取文件,并在每一行上测试是否在第9次找到要查找的字符串。这样做的一种方法是:

代码语言:txt
复制
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.
    } 
}

使用:

代码语言:txt
复制
$n = 4;
$needle = '<!--TYPEA-->';
$lineNumber = getLineNumber($n, $needle);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/-100002137

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档