4

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

2 Answers 2

3

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;
?>
Sign up to request clarification or add additional context in comments.

2 Comments

Hi Chris, I'm getting the output something like this. 2424acronichally 25252525acronycally 262626acronychally 272727272727acronymically 28282828282828282828282828acropetally 29292929acrophonically
Oops, I put the echo inside the while loop. Just knock it down a line, I'll update my answer now. - There we go. That should work nicely.
1

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

2 Comments

Would it not be better to avoid searching the pattern a 2nd time if they're already doing it once? Given a large file, this might cause unnecessary lag issues. Would make more sense to me to put something inside the already-present loop.
That worked!! Chris!!. Thanks alot!! Now I have to check the script given by @Gabriel.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.