Php prag\u match\u如何计算多次出现的次数

Php prag\u match\u如何计算多次出现的次数,php,preg-match-all,Php,Preg Match All,我有以下样本: $text=" the line the line the line also remember this line the line also remember this line "; 我需要知道找到该行时重复了多少次 UPD: 好啊假设我不需要数一数。我需要与该示例匹配的表达式。请记住,我想记住这一行。该行在不同的行中以不同的数字出现了几次 UPD2: $text=“行150。行150。”; preg_match_all(“/(行)[0-9]+\./i”,$text,$m

我有以下样本:

$text="
the line
the line
the line
also remember this line
the line
also remember this line
";
我需要知道找到该行时重复了多少次

UPD: 好啊假设我不需要数一数。我需要与该示例匹配的表达式。请记住,我想记住
这一行
。该行在不同的行中以不同的数字出现了几次

UPD2:

$text=“行150。行150。”;
preg_match_all(“/(行)[0-9]+\./i”,$text,$matches);
打印(匹配项);

我希望匹配的是
第150行。
第150行。

表达式只匹配句子的第一部分,而不匹配第二部分。这就是我的问题所在。

从中可以传递一个数组来保存字符串的所有匹配项。如果您从该阵列中获取计数,您将准确地找到您需要的:

<?php

$text="
the line
the line
the line
also remember this line
the line
also remember this line
";
preg_match_all('/the line/', $text, $matches);

echo count($matches[0]);

这是一个完美的用例,只需像这样使用它:

echo substr_count($text, "the line");
输出:

4

preg\u match\u all
是一种方法,但请记住,使用正则表达式会带来一些负面影响。因此,记住这一点,尽可能使用
字符串
函数

如果您只想知道子字符串的出现次数,那么
substr\u count
可能更容易使用

$needle = 'the line';
$count = substr_count($text, $needle);

echo $count;

如果你想让它不区分大小写,就把针线和干草堆都小写。

你试过什么或做过什么研究吗?那么这个问题我们在哪里?下面的答案解决了你的问题吗?更新2的代码对我来说很好!请详细说明您的问题!我需要把`第150行'和`第150行'归还。这是我能使用的最接近的表达。请将您的预期输出添加到您的问题中!