开发者

string min,max length function

开发者 https://www.devze.com 2023-02-10 14:00 出处:网络
I\'m trying to check min and max length of strings: If I pass it an array, such as follows, I want the values to be returned if true and NULL if false:

I'm trying to check min and max length of strings:

If I pass it an array, such as follows, I want the values to be returned if true and NULL if false:

$lenghts = array('a' => array('min' => 20, 'max' => 70),
                 'b' => array('min' => 50, 'max' => 800),
                 'c' => array('min' => 3,  'max' =开发者_JAVA技巧>8));

And the values are:

$values = array('thread_title' => 'this is it', 'thread_content' => 'this is not it', 'thread_tags' => 'also not it')

;

EDIT

It's like 5am here (really quite sleepy), I should copied and pasted the correct version, sorry:

function string_min_max($string_array, $array)
{
   $returns = array();  # store returned values
   foreach ($array as $key)
   {
      #  check for minimum:
      if (array_key_exists('min', $key))
      {
         $minimum = (strlen($string_array[$key]) < $key['min'] ? $key = NULL : $key);
      }

      if (array_key_exists('max', $key))
      {
         $maximum = (strlen($string_array($key)) > $key['max'] ? $key = NULL : $key);
      }

      if ($minimum !== NULL && $maximum !== NULL)
      {
         $returns[$key]['min'] = $minimum;
         $returns[$key]['max'] = $maximum; 
      }
   }
}

This does not work:

   string_min_max($values, $lengths);


This code is reducable to:

function string_min_max($array)
{
   $returns = array();  # store returned values
   foreach ($array as $key)
   {
      #  check for minimum:
      if (TRUE)
      {
         $minimum = (FALSE ? $key = NULL : $key);
      }
   }
}

OR:

function string_min_max($array)
{
   $returns = array();  # store returned values
   foreach ($array as $key)
   {
      $minimum = $key;
   }
}

OR:

function string_min_max($array)
{
   $returns = array();  # store returned values
}

OR:

(void)

So the answer is: no. It won't work.


Without looking too much at the details, one obvious problem is that you are not returning anyting from your function; you are building an array but you don´t use it so it gets destroyed at the moment your function ends.

I think that at least you will need this at the end of your function:

  return $returns;
}         // end function

You can then call your function like:

$results = string_min_max($values, $lenghts);


if use this for validate string by length and chars :

function checkString($string, $regex, $minlenght = 3, $maxlenght = 20) {
        if(preg_match($regex, $string) && strlen($string) >= $minlenght && strlen($string) <= $maxlenght) return true;
        return false;
}
0

精彩评论

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