PHP limit length of every string in array

前端 未结 3 1434
名媛妹妹
名媛妹妹 2021-01-16 20:26

I have an array with multiple strings, like this:

$str[0] = \"kasdnkjsandjabsdkjsbad\";
$str[1] = \"kasdnkjsandjasdjksabdjkasbkjdsak\";
$str[2] = \"kasdnkjsa         


        
3条回答
  •  南方客
    南方客 (楼主)
    2021-01-16 21:15

    Well, theoretically, this is pretty simple: just create a function that will "limit" the length of the string, and if it's too long, strip it off:

    EDIT: if you want to "limit" the number of characters while adding them to the array, you can simply create a check in a function:

     $length ) {
            return false;
        }
        return $array[] = $value;
    }
    
    $strings = array( );
    
    append( $strings, 'kasdnkjsandjabsdkjsbad' ); // is accepted.
    append( $strings, 'kasdnkjsandjabsdkjsbadkasdnkjs' ); // is not accepted
    append( $strings, 'kasdnkjsandsadbaskjdbsakjdbasdsadjsadjksabdk' ); // is not accepted.
    
    
    
    // if you *really* want to exit when a value is too long:
    function append_exit( $array, $value, $length = 25 ) {
        if( mb_strlen( $value ) > $length ) {
            trigger_error( 'Value is too long.', E_USER_ERROR );
            exit;
        }
        return $array[] = $value;
    }
    

提交回复
热议问题