好吧,从理论上讲,这很简单:只需创建一个“限制”字符串长度的函数,如果太长,将其删除:
<?php
$str = array( );
$str[0] = "kasdnkjsandjabsdkjsbad";
$str[1] = "kasdnkjsandjasdjksabdjkasbkjdsak";
$str[2] = "kasdnkjsandsadbaskjdbsakjdbasdsadjsadjksabdk";
$str[3] = "kasdnkjsandasdjbaskdbjsakbdkjsabdjksabdkjsabdjkasbdjksa";
$str[4] = "kasdnkjsandsajdbaskjdbjksabdjkbasjkdbjksadbjksadbjksadbjksadbkjsa";
$str[5] = "kasdnkjsandasdjbsakdjbsakjdbsakjdsakjdbjksabdjksabdkjasbkjdasbkjdbsakjdsabjk";
$length = 10;
$substr = function( $element ) use ( $length ) {
return substr( $element, 0, $length );
};
$str = array_map( $substr, $str );
var_dump( $str );
编辑:如果您想在将字符添加到数组时“限制”字符数,您可以简单地在函数中创建一个检查:
<?php
function append( &$array, $value, $length = 25 ) {
if( mb_strlen( $value ) > $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;
}