Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count lines in textarea including automatic line breaks

I have a textarea

<textarea id="text" name="text" rows="6"></textarea>

<style>
    #text { width: 30%; }
</style>

When submitting the form, I need to check if the input exceeded 6 rows. I have a JS code, which checks for scrollbar (scrollbar present = more than 6 lines = invalid input) which works perfectly. The tricky part is, how can validate the input with PHP in case of disabled JS?

I tried something like this

public function overflowValidator($input, $maxLines, $cols) {
    $linebreakCount = substr_count($input, "\n");
    $overflow1 = ($linebreakCount <= $maxLines);
    $overflow2 = (ceil(strlen($input) / $cols) <= $maxLines);
    return $overflow1 && $overflow2;
}

The biggest problem is that the width of the textarea is dynamic (responsive design) so I can't easily tell how many letters fit into one line. I'm afraid this can't be solved but maybe there is a solution I'm not aware of...

like image 202
Michal Artazov Avatar asked Oct 16 '25 13:10

Michal Artazov


1 Answers

Count total lines :-

$lines = preg_split('/\n|\r/',$str);
$Total_lines = count($lines); 
echo $Total_lines;
like image 88
Arshid KV Avatar answered Oct 18 '25 07:10

Arshid KV



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!