问题描述
我正在尝试在php页面中创建一个多行textarea,我想验证如果用户不能每行插入超过50个字符,或超过50行。
想法是用户可以粘贴电子表格中的内容,但如果一行超过50个字符,其余行将被丢弃,而不会插入下一行。这就是为什么我要避免使用50个单独的文本框的想法。
I'm trying to create a multiline textarea in a php page, and I want to validate so that if the user can't insert more than 50 characters per line, or more than 50 lines.The idea is that the user can paste something from a spreadsheet, but if one line has more than 50 characters, the rest will be discarded, and not inserted in the next line. That's why I want to avoid the idea of having 50 individual textboxes.
如果可以在javascript(或php本身,但我没有)这样做是理想的在php中看到了类似的东西。
It would be ideal if this could be done in javascript (or php itself, but I didn't saw anything like it in php).
谢谢!
更新:感谢所有答案,但是只有在用户提交表单后才能工作,对吧?
例如,如果最大行数为3而不是50,并且用户插入100个连续字符,然后换行,则只剩下50个字符,将输入限制为2而不是3.
希望我很清楚...
UPDATE: Thanks for all that answers, but that would work only after the user submitted the form, right?For example, if the max lines is 3 instead of 50, and the user inserts 100 consecutive characters, and then a line break, it would only have 50 characters left, limiting the inputs to 2 instead of 3.Hope I was clear...
推荐答案
这是基于马修提供的代码,但这个更短并限制行数。
Here it is, based on the code provided by Matthew, but this 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);
这篇关于每行的字符数和每个textarea限制的行数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!