Steve Price
Steve Price

Reputation: 600

Extracting the digits after the final underscore in a string

I have a string that could contain any of the following:

120_254 or 120_254_65 or 140_260_220_45 or 10_210_250_55_100

I need to be able to strip ANY of the above examples to just the digits after the last underscore. I think i can use ltrim for this but i don't know how to code it when there are multiple instances of the underscore.

Upvotes: 0

Views: 624

Answers (3)

Sougata Bose
Sougata Bose

Reputation: 31749

Try with -

$last = substr($str, strrpos($string, "_", -1) + 1);
var_dump($last);

strrpos($string, "_", -1) will return the last _'s position.

Or you can use explode()

$digits = explode('_', $data);
$last   = $digits[count($digits)-1];

Upvotes: 1

munsifali
munsifali

Reputation: 1733

try this substr:

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

$str will return the following output 100

Upvotes: 0

Valentin Rodygin
Valentin Rodygin

Reputation: 864

You can use explode to get an array from the string and array_pop to get the last item:

$last = array_pop( explode( "_", $str ) );

Upvotes: 1

Related Questions