How to get the last char of a string in PHP?

前端 未结 12 1419
说谎
说谎 2020-12-04 05:24

I need to get the last character of a string. Say I have \"testers\" as input string and I want the result to be \"s\". how can I do that in PHP?

12条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-04 05:43

    I can't leave comments, but in regard to FastTrack's answer, also remember that the line ending may be only single character. I would suggest

    substr(trim($string), -1)
    

    EDIT: My code below was edited by someone, making it not do what I indicated. I have restored my original code and changed the wording to make it more clear.

    trim (or rtrim) will remove all whitespace, so if you do need to check for a space, tab, or other whitespace, manually replace the various line endings first:

    $order = array("\r\n", "\n", "\r");
    $string = str_replace($order, '', $string);
    $lastchar = substr($string, -1);
    

提交回复
热议问题