PHP limit length of every string in array

前端 未结 3 1380
名媛妹妹
名媛妹妹 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:08

    I am assuming you want to iterate through each string in the array and trim it to a specific length.

    Create a function that does this to a single string (as an argument). Use array_map to apply this function to each element in the array.

    Try this yourself - if you have any problems, append your attempt to your question.

    0 讨论(0)
  • 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:

    <?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 );
    

    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:

    <?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;
    }
    
    0 讨论(0)
  • 2021-01-16 21:29

    you could use

    substr( $myString, $startInt, [$endInt] );
    

    to limit each string to only so many characters. An Example:

    for( $i = 0; $i < sizeof( $myArray ); $i++ ){
        $myArray[$i] = substr( $myString, 0, 20 );
    }
    

    That will limit the strings to 20 characters in length, if I did that right.

    0 讨论(0)
提交回复
热议问题