在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;
?>

相关文章

统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
前言 之前做了微信登录,所以总结一下微信授权登录并获取用户...
FastAdmin是我第一个接触的后台管理系统框架。FastAdmin是一...
之前公司需要一个内部的通讯软件,就叫我做一个。通讯软件嘛...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...