Characters per line and lines in a text box

I am trying to create multi-line textarea on a php page and I want to check if the user cannot insert more than 50 characters per line or more than 50 lines. The idea is that the user can insert something from the spreadsheet, but if one row contains more than 50 characters, the rest will be discarded and will not be inserted into the next row. Therefore, I want to avoid the idea of ​​having 50 separate text fields.

It would be ideal if this could be done in javascript (or php itself, but I have not seen anything like it in php).

Thanks!

UPDATE: Thanks for all the answers, but this will only work after the user submits the form, right? For example, if the maximum lines are 3 instead of 50, and the user inserts 100 consecutive characters and then breaks the line, he will leave only 50 characters, limiting the input to 2 instead of 3. I hope I understand ...

+3
source share
5 answers

Here it is based on the code provided by Matthew, but it is shorter and also limits the number of lines.

$lines = array_slice(explode("\n", $string), 0, 50); // max 50 lines

foreach ($lines as $key => $value)
{
    $lines[$key] = substr(trim($value), 0, 50); // max 50 chars
}

$string = implode("\n", $lines);
+1
source

PHP:

$max_length = 50;
$lines = explode("\n", $input);
for($i = 0; $i < count($lines); $i++)
{
    $lines[$i] = rtrim($lines[$i]); // just incase there a "\r"
    $lines[$i] = (strlen($lines[$i]) <= 50 ? 
                      $lines[$i] : 
                      substr($lines[$i], 0, 50));
}
$input = implode("\n", $lines);
+1
source

:

1: jQuery ( JavaScript, ) 50- . , .

2: php , JavaScript . JavaScript ( Ajax)

, , \n, . 50 . , , .

+1

explode ( "\n" , $str), , .

You can use a similar method at the end of the user interface using Javascript, but if you want to ensure security, you must do this at the end of PHP, because Javascript can be bypassed.

Ultimately, it depends on whether the user’s life is easier or bad things are prevented.

0
source

Find the length of the longest string:

$length = array_reduce(array_map(explode("\n", $string), 'strlen'), 'max', 0);
0
source

Source: https://habr.com/ru/post/1716491/


All Articles