1

My questions is somewhat based off this: How can I get the last 7 characters of a PHP string?

Mine is similar. I need to get the last x characters of a string and to stop when I reach "-"

for example, I have a booking code: N-903

and I can get the last 3 characters like so:

$booking_Code = N-903
$booking_Code = substr($booking_Code, -3);

and the result will be:

903

This number however will increase, so I expect to see booking codes like:

N-1001
N-22520
N-201548

so the code:

substr($booking_Code, -3);

would become useless. Is there any way to use "-" as a delimiter? I think that's the correct term to use. because the number that's generated will always come after the hyphen "-". Any help would be greatly appreciated

Community
  • 1
  • 1
Akira Dawson
  • 1,247
  • 4
  • 21
  • 45

2 Answers2

3

try this

<?php
$tmpArray = explode("-",$mystr);
echo $tmpArray[1];

?>

You might want to refer to explode function in php.

Satya
  • 8,693
  • 5
  • 34
  • 55
2

As an alternative, you could also use strrchr in conjunction with the substr you have:

$booking_Code = 'N-903';
$booking_Code = substr(strrchr($booking_Code, '-'), 1);
echo $booking_Code; // 903
Kevin
  • 41,694
  • 12
  • 53
  • 70
  • I like this one too. Would this be applicable if I had multipl hyphens in my string? e.g N-07-03-903 I would need the the digits after the last hyphen! – Akira Dawson Apr 22 '15 at 02:00
  • 1
    @AkiraDawson yes, that would be the beauty of it, you'd still get that last digits from the last `-`. `explode()` can cover that issue as well, just use `end()`. it'll get the last exploded element instead of pointing directly into the index – Kevin Apr 22 '15 at 02:02