0

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?

1
  • 1
    Your problem isn't with strrpos(), it's with substr(). Read the documentation. Commented Feb 1, 2013 at 5:51

9 Answers 9

5

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.

Sign up to request clarification or add additional context in comments.

Comments

2

Try:

array_pop(split('_', $string));

Codepad Example: http://codepad.org/JkOaS0oc

Comments

2

You may want to use explode instead.

echo end(explode('_', $string));

1 Comment

I like end, but exploding seems more "expensive" than substr.
2

Try this:

 array_pop(explode('_', $string));

Comments

1

Try

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

Comments

1

Try:

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

Comments

1

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.

Comments

1

try this easy way using explode()

$string = 'abc_123_test';
$string = explode('_',$string);
print_r($string);
echo $string[2]; //output test

Comments

0

You can just try this code to get 'test' from following string

$string = 'abc_123_test';

echo substr($string,8,11);

best luck

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.