How can I get the last value after a specific delimiter in a string?

I have a string of numbers stored in $numbers

:

3,6,86,34,43,52

      

What's the easiest way to get the last value after the last comma? In this case, the number 52 will be the last value that I would like to store in a variable.

The number can vary in size, so try:

substr($numbers, -X)

      

doesn't help me i guess.

How to get the number after the last comma in a line, any idea?

+3


source to share


5 answers


This should work for you:

Just use strrpos()

to get the position of the last comma and then use substr()

to get the line after the last comma, like

$str = "3,6,86,34,43,52";
echo substr($str, strrpos($str, ",") + 1);

      



output:

52

      

+4


source


Just explode the string with a delimiter character and select the last token received:

<?php
$string = '3,6,86,34,43,52'; 
$tokens = explode(',', $string);
echo end($tokens);

      

An alternative would be to use a regular expression:



<?php
$string = '3,6,86,34,43,52'; 
preg_match('/,([0-9]+)$/', $string, $tokens);
echo end($tokens);

      

Personally, I am of the opinion that efficiency is less important than how easy it is to read and understand code these days. Computing power is cheap, developers are expensive. This is why I would use the first approach while waiting for the number of items in a row to get large.

0


source


You can do it like this:

$numbers = "3,6,86,34,43,52";
$arr = explode(",",$numbers);

echo $arr[count($arr)-1];

      

0


source


I just put explode

it into an array and get the last element:

$numbers = '3,6,86,34,43,52';
$arr = explode(',', $numbers);
echo $arr[count($arr) - 1];

      

0


source


if the string can have spaces then use preg_split

$str = '3,6,86, 34,43 ,52';

$nums = preg_split('/\s*,\s*/', $str);
echo end($nums);  // 52

      

0


source







All Articles