KumarRana
KumarRana

Reputation: 103

count words of regex pattern in php?

I'm trying to match pattern 'lly' from '/usr/share/dict/words' in linux and I can display them in the browser. I want to count how many words that matches the pattern and display the total at the end of output. This is my php script.

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

Upvotes: 4

Views: 557

Answers (2)

Gabriel Moretti
Gabriel Moretti

Reputation: 676

PHP: Glob - Manual

sizeof(glob("/lly/*"));

@edit

Also, you can do like this:

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

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

echo count($array);

Upvotes: 1

Chris Evans
Chris Evans

Reputation: 1265

You can use the count function to count how many elements of an array they are. So you simply just add to this array each time, and then count it.

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

A simpler way if you don't want to store all of the values (which might come in handy, but anyway) is to just increment to an integer variable like so:

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

Upvotes: 3

Related Questions