douxianxing5712 2013-02-01 05:49
浏览 105
已采纳

PHP如何使用substr和strrpos在最后检索字符串

I have this string abc_123_test and I am trying to get just "test" from the string. I have this code currently.

$string = 'abc_123_test';

$extracted_string = substr( $string, 0, strrpos( $string, '_' ) );

However this gets the first part of the string, everything up to 'abc_123'. So it seems it is reverse of what I wanted. I thought by using strrpos, it will get the reversed but obviously I am missing something.

Any help?

  • 写回答

9条回答 默认 最新

  • dongmacheng3222 2013-02-01 05:53
    关注

    strrpos does reverse the sense in that it looks for the final one, but you're still doing the substring from the start of the string to that point.

    You can use:

    substr ($string, strrpos( $string, '_' ) + 1 );
    

    to get the final bit of the string rather than the starting bit. This starts at the position one beyond the final _ and, because you omit the length, it gives you the rest of the string.

    There are no doubt better ways to achieve this but, if you're limiting yourself to substr and strrpos, this will work fine.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(8条)

报告相同问题?