在php中计算正则表达式模式的单词数?

在php中计算正则表达式模式的单词数?,php,regex,linux,Php,Regex,Linux,我正在尝试匹配linux中“/usr/share/dict/words”中的模式“lly”,我可以在浏览器中显示它们。我想计算与模式匹配的单词数,并在输出的末尾显示总数。这是我的php脚本 <?php $dfile = fopen("/usr/share/dict/words", "r"); while(!feof($dfile)) { $mynextline = fgets($dfile); if (preg_match("/lly/", $mynextline)) echo "$myn

我正在尝试匹配linux中“/usr/share/dict/words”中的模式“lly”,我可以在浏览器中显示它们。我想计算与模式匹配的单词数,并在输出的末尾显示总数。这是我的php脚本

<?php
$dfile = fopen("/usr/share/dict/words", "r");
while(!feof($dfile)) {
$mynextline = fgets($dfile);
if (preg_match("/lly/", $mynextline)) echo "$mynextline<br>";
}
?>

您可以使用count函数计算数组中的元素数量。因此,您只需每次添加到此数组,然后对其进行计数

<?php
$dfile = fopen("/usr/share/dict/words", "r");
//Create an empty array
$array_to_count = array();
while(!feof($dfile)) {
$mynextline = fgets($dfile);
if (preg_match("/lly/", $mynextline)){
    echo "$mynextline<br>";
    //Add it to the array
    $array_to_count[] = $mynextline;
}
}
//Now we're at the end so show the amount
echo count($array_to_count);
?>

@编辑

此外,您可以这样做:

$array = glob("/usr/share/dict/words/lly/*")

foreach ($array as $row)
{
    echo $row.'<br>';
}

echo count($array);
$array=glob(“/usr/share/dict/words/lly/*”)
foreach($array作为$row)
{
回显$row。“
”; } 回波计数($阵列);
如果他们已经搜索了一次,那么避免第二次搜索模式不是更好吗?如果文件很大,这可能会导致不必要的延迟问题。对我来说,在已经存在的循环中放入一些东西会更有意义。这很有效!!克里斯!!。非常感谢!!现在我必须检查@Gabriel.Hi Chris给出的脚本,我得到的输出是这样的。2424首字母缩写25252525首字母缩写262626首字母缩写为282882828282828282828282828首字母缩写为292929292929首字母缩写,我把回声放在while循环中。只要把它写下来,我现在就更新我的答案好了。这应该很有效。
sizeof(glob("/lly/*"));
$array = glob("/usr/share/dict/words/lly/*")

foreach ($array as $row)
{
    echo $row.'<br>';
}

echo count($array);