Reputation:
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?
Upvotes: 0
Views: 6504
Reputation: 13728
try this easy way using explode()
$string = 'abc_123_test';
$string = explode('_',$string);
print_r($string);
echo $string[2]; //output test
Upvotes: 1
Reputation: 547
You can just try this code to get 'test' from following string
$string = 'abc_123_test';
echo substr($string,8,11);
best luck
Upvotes: 0
Reputation: 4128
I think you need to use the below code:
$extracted_string = substr( $string, strrpos( $string, '_' )+1);
substr( $string, 0, strrpos( $string, '_' ) ); - this starts from 0th position.
Upvotes: 1
Reputation: 881113
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.
Upvotes: 5
Reputation: 7821
You may want to use explode instead.
echo end(explode('_', $string));
Upvotes: 2
Reputation: 15379
Try:
array_pop(split('_', $string));
Codepad Example: http://codepad.org/JkOaS0oc
Upvotes: 2