-4

Possible Duplicate:
PHP strlen question

how to check if text from post field is 8 - 20 characters long? Is it done with strlen, and could you give me some example, please?

Community
  • 1
  • 1
Y2ok
  • 171
  • 1
  • 2
  • 10

4 Answers4

0

It's easy:

$item = $_POST['item'];
if (strlen($item) >= 8 && strlen($item) <= 20) { /*do something*/ }

Good luck! Konstantin

Konstantin Yovkov
  • 62,134
  • 8
  • 100
  • 147
0
$variable = $_POST['your-field-name']; // or $_GET['']; depends on your post method

if(strlen($variable) > 7 && strlen($variable) < 21) {
 return true;
} else {
 return false;
}
Grigor
  • 4,139
  • 10
  • 41
  • 79
  • and what will happen if I use if(strlen($variable) > 7 || strlen($variable) < 21) instead of &&? – Y2ok Oct 19 '11 at 17:14
  • any number would work because 0 is smaller than 21 and 30 is larger than 7, || checks for one of the conditions to be true – Grigor Oct 19 '11 at 18:03
0
<?php

// get the length of the text. we take the value by reference
// because there is the risk it doesn't exist (such as when
// no data is submitted).
$textLen = strlen($myTextField = &$_POST['my_text_field']);

// test its length
if ($textLen >= 8 && $textLen <= 20) {
    echo 'Text is the right length.';
} else {
    echo 'Text is the wrong length.';
}
erisco
  • 14,154
  • 2
  • 40
  • 45
0

The easiest option is to use strlen:

strlen($_POST['shinyHappyString']) > 7 && strlen($_POST['shinyHappyString']) < 21

However, if you encounter multi-byte strings, you are in trouble. Therefore I recommend you to use grapheme_strlen or mb_strlen instead. You can check how they use it in Symfony2's validators.

Ondrej Slinták
  • 31,386
  • 20
  • 94
  • 126