prag_match_all如何计算多次出现次数

时间:2015-05-01 16:58:00

标签: php preg-match-all

我有以下样本:

$text="
the line
the line
the line
also remember this line
the line
also remember this line
";

我需要知道the line在被发现时重复多少次。

UPD: 好。假设我不需要数数。我需要与该样本匹配的表达式。请记住,我想记住the line。在不同的行中,该行有多次出现不同的数字。

UPD2:

$text=" the line 150. the line the line 150."; preg_match_all("/ (the line) [0-9]+\./i",$text,$matches); print_r($matches);

我希望匹配为the line 150.the line the line 150.

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

3 个答案:

答案 0 :(得分:3)

这是substr_count()的完美用例,只需使用它:

echo substr_count($text, "the line");

输出:

4

答案 1 :(得分:2)

preg_match_all是一种可行的方法,但请记住,使用正则表达式会有一些惩罚性能。因此,请尽可能使用string函数。

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

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

echo $count;

如果你想让它不区分大小写只需要针和大海捞针。

答案 2 :(得分:1)

documentation,你可以传递一个数组来保存字符串的所有匹配项。如果你从这个阵列中获取计数,你就会找到你需要的东西:

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