Search code examples
phpstringsubstr

Get part of a string after n spaces


if I have a string for example like this :

$text = '12 24 40 59 101 302 340 ';

How do I always get the last number (in this case 340), care there is also a space at the end, which I dont want :x, also the last number can be a 1 digit number or even a 10 digit number so just getting the last 4 chars of the string and then removing the space won't work :) ty in advance for your help!


Solution

  • This should do the trick:

    $text = trim('12 24 40 59 101 302 340 ');
    $value = end(explode(" ", $text));
    

    Explanation:

    trim() removes the space at the end of your string. explode() converts the string to an array divided by space and end() takes the last value of that array