我正在尝试在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);
?>
如果你不想存储所有值(这可能会派上用场,但无论如何),一种更简单的方法是只增加到一个整数变量,如下所示:
<?PHP
$dfile = fopen("/usr/share/dict/words", "r");
//Create an integer variable
$count = 0;
while(!feof($dfile)) {
$mynextline = fgets($dfile);
if (preg_match("/lly/", $mynextline)){
echo "$mynextline<br>";
//Add it to the var
$count++;
}
}
//Show the number here
echo $count;
?>