我有一个包含多个字符串的数组,如下所示:
$str[0] = "kasdnkjsandjabsdkjsbad";
$str[1] = "kasdnkjsandjasdjksabdjkasbkjdsak";
$str[2] = "kasdnkjsandsadbaskjdbsakjdbasdsadjsadjksabdk";
$str[3] = "kasdnkjsandasdjbaskdbjsakbdkjsabdjksabdkjsabdjkasbdjksa";
$str[4] = "kasdnkjsandsajdbaskjdbjksabdjkbasjkdbjksadbjksadbjksadbjksadbkjsa";
$str[5] = "kasdnkjsandasdjbsakdjbsakjdbsakjdsakjdbjksabdjksabdkjasbkjdasbkjdbsakjdsabjk";
我有什么办法可以限制所有数组的字符串长度,假设我不知道某个数组中将有多少个字符串.
谢谢,
解决方法:
好吧,从理论上讲,这很简单:只需创建一个将“限制”字符串长度的函数,如果它太长,请将其剥离:
$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 );
编辑:如果您要“限制”字符数,同时将它们添加到数组中,则可以简单地在函数中创建一个检查:
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;
}
标签:php,arrays
来源: https://codeday.me/bug/20191010/1885090.html