user381800
user381800

Reputation:

PHP how to retrieve string at the end with substr and 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?

Upvotes: 0

Views: 6504

Answers (9)

Rakesh Sharma
Rakesh Sharma

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

Swapnil T
Swapnil T

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

Sankar V
Sankar V

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

William Buttlicker
William Buttlicker

Reputation: 6000

Try this:

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

Upvotes: 2

Raioneru
Raioneru

Reputation: 151

Try:

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

Upvotes: 1

inhan
inhan

Reputation: 7470

Try

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

Upvotes: 1

paxdiablo
paxdiablo

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

Achrome
Achrome

Reputation: 7821

You may want to use explode instead.

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

Upvotes: 2

Daniel Li
Daniel Li

Reputation: 15379

Try:

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

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

Upvotes: 2

Related Questions