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?
strrposdoes 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:
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
substrandstrrpos, this will work fine.