How can I get the last 7 characters of a PHP string?

后端 未结 7 2045
太阳男子
太阳男子 2020-11-30 18:25

How would I go about grabbing the last 7 characters of the string below?

For example:

$dynamicstring = \"2490slkj409slk5409els\";
$newstring = some_f         


        
相关标签:
7条回答
  • 2020-11-30 18:50

    Safer results for working with multibyte character codes, allways use mb_substr instead substr. Example for utf-8:

    $str = 'Ne zaman seni düşünsem';
    echo substr( $str, -7 ) . ' <strong>is not equal to</strong> ' .
      mb_substr( $str, -7, null, 'UTF-8') ;
    
    0 讨论(0)
  • 2020-11-30 18:52

    For simplicity, if you do not want send a message, try this

    $new_string = substr( $dynamicstring, -min( strlen( $dynamicstring ), 7 ) );
    
    0 讨论(0)
  • 2020-11-30 18:59

    Use substr() with a negative number for the 2nd argument.

    $newstring = substr($dynamicstring, -7);
    

    From the php docs:

    string substr ( string $string , int $start [, int $length ] )

    If start is negative, the returned string will start at the start'th character from the end of string.

    0 讨论(0)
  • 2020-11-30 19:00

    It would be better to have a check before getting the string.

    $newstring = substr($dynamicstring, -7);
    

    if characters are greater then 7 return last 7 characters else return the provided string.

    or do this if you need to return message or error if length is less then 7

    $newstring = (strlen($dynamicstring)>7)?substr($dynamicstring, -7):"message";
    

    substr documentation

    0 讨论(0)
  • 2020-11-30 19:02

    umh.. like that?

    $newstring = substr($dynamicstring, -7);
    
    0 讨论(0)
  • 2020-11-30 19:02

    last 7 characters of a string:

    $rest = substr( "abcdefghijklmnop", -7); // returns "jklmnop"

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