微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

我正在尝试在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;
?>

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐