开发者

How to Limit Text Characters in PHP?

I was wondering how can I limit a users input like HTML maxlength attribute but with PHP, example would be nice? Is MySQL varchar(255) o开发者_StackOverflowne way to limit a users character input? What are the cons of just counting on MySQL to do this?


Have you taken a look at strlen?

$input = $_GET['input'];
if ( strlen($input) > 255 ){
    throw new Exception('Cannot have input exceeding 255 characters');
}

The main issues of counting on MySQL to truncate the length of a string is the lack of error handling. If users input has been truncated to a length they probably don't intend it to be and it would (probably) be better to display an error page.


substr($string, $start, $length)

This will cut a string short for you.

$start should be 0 to start from the first character

$length is how long you want the string to be.


Passively shortening input without notice is bad. Throwing an error is better. But in my opinion the best solution is to keep the user from typing too much in the first place. This is easy for fields:

<input maxlength="255" />

Most browsers will prevent the user from typing more than that. <textarea> is more difficult to limit, but it can be done with some simple javascript. Twitter does this. Consider the following example, which displays a character count above the textarea:

<html>

<script type="text/javascript">
  function numberOfCharacters(textbox,limit,indicator) {
    chars = document.getElementById(textbox).value.length;
    document.getElementById(indicator).innerHTML = limit-chars;
  }
</script>

<body>
  <label for="mytextbox">
    Message (140 char. max.)
    <span id="characterlimit">140</span>
  </label>
  <br/>
  <textarea id="mytextbox" rows="2" cols="40" onkeyup="numberOfCharacters('mytextbox',140,'characterlimit');"></textarea>
</body>

</html>

This crude example does not enforce the character limit, but it does notify the user of the limit. Use this in combination with Yacoby's strlen() example to throw an error if the user ignores the warning and exceeds the limit anyway. At that point you've done all you can to prevent excessive typing, and the user only has himself to blame.

If you are going to impose a character limit, it is common courtesy to notify the user before he types a novel, and to keep count for him.


strlen() is one of the slowest functions in whole PHP. Best solution is:

<?php
$text = "some text";
if (isset($text[255])) {
    echo 'Text is too long. It should be no longer than 255 characters';
}
?>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜