Count Number Of Words In a Textarea

I have a text area that gets input from a PHP script, and I would like to count the number of words or line breaks in the textarea and echo it below the text area.

This is what the code looks like for the textarea.

<textarea name="domains" cols="120" rows="5" style="max-width:100%;">
    <?php $output_array = explode(" ",$output);
    $count = count($output_array);
    for ($i=0;$i<$count;$i++){
    echo $output_array[$i]."\n";
    }
    ?>
</textarea><br />
<br>
        <?php
        preg_match_all("/(\n)/", $_POST['domains'], $matches);
         $total_lines = count($matches[0]) + 1;
         echo $total_lines;
        ?>
        <br />

I tried using preg_match_all but the output I get is only "1", regardless of how many line breaks are inside the text area.

2 answers

  • answered 2021-04-21 15:33 RiggsFolly

    $str = 'as aa frd sad as
    kjhsdf sdkjh 
    sd sdkjhsdf
    sjkldhfh sdfjh sd';
    
    
    preg_match_all("/\w+/", $str, $matches);
    echo 'Words = ' . count($matches[0]);
    echo PHP_EOL;
    preg_match_all("/\n/", $str, $matches);
    echo 'newlines = ' . count($matches[0]);
    echo PHP_EOL;
    echo 'So number of line is = ' . count($matches[0])+1;
    

    RESULT

    Words = 12
    newlines = 3
    So number of line is = 4
    

  • answered 2021-04-21 17:51 Lajos Arpad

    You can do the following:

    $arr = array_filter(explode(" ", $input) function($item) {
        return !!$item;
    });
    
    $count = count($arr) + count(explode("\n", implode(",", $arr)));
    

    This splits the string by space, filters out empty items to avoid issues due to multiple spaces found between words, then glues the array back into a string, splits it by newline and adds the two counts together.