Stack crawler
Stack crawler

Reputation: 379

Enforce a maximum byte count in an HTML textarea field

I'm trying to limit the number of entered unicode characters in a textarea to 500.
When I try to post the form and get the textarea content to check its length in the back-end, I get a double length, meaning the value I get from strlen is twice the number of the inputted characters.

What is the problem here?

<textarea id="ArticleSummary" name="ArticleSummary" rows="4" maxlength="500">
 <?php echo $Summary; ?></textarea>
  $Summary = trim( $_POST['ArticleSummary'] );
  echo strlen($Summary);

Upvotes: 0

Views: 2076

Answers (3)

wadziu
wadziu

Reputation: 26

I don't know where from you are taking variable $Summary;but if it is longer than your required 500 signs it will be sent as is. Example code below:

<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
</head>
<body>

<?php empty($_POST['ArticleSummary']) or var_dump(mb_strlen($_POST['ArticleSummary']));?>
<form method="POST" action="">
<?php $text = '123456789'; ?>

<textarea id="ArticleSummary" name="ArticleSummary" rows="4" maxlength="5"><?php echo $text;?></textarea>

<input value="submit" type="submit" />

</form>

</body>
</html>

Upvotes: 0

Radley Sustaire
Radley Sustaire

Reputation: 3399

I know this is an old question, but it was a top result in Google. See this answer about line breaks \n in html/JavaScript and \r\n in PHP.

Also note that you want to use mb_strlen because certain characters, like emoji, will count as multiple characters in PHP.

Here is the solution:

// <textarea maxlength="2500">🎌🎌🎌...</textarea>

echo strlen( $text ); // 5132 (incorrect)
echo mb_strlen( $text ); // 2566 (incorrect)

$text = preg_replace( "/\r\n|\r/", "\n", $text );

echo mb_strlen($order_notes); // 2500 (correct)

Upvotes: 0

in need of help
in need of help

Reputation: 1622

unicode characters take 2 bytes each and strlen returns the number of bytes in the string, you can transform it to unicode characters and check the length.

Upvotes: 1

Related Questions