Jump to content

Test if string ends in -[number]


John_A

Recommended Posts

I've got a string which is usually abc-def-0123 but it sometimes has an additional dash and then a single digit (e.g. ghi-jkl-4567-1).

 

It's always the same pattern and length, (three letters, a dash, three letters, a dash, 4 digits then the possibility of a dash followed by a single digit).

 

What's the best way to test if the string ends in a dash followed by a single digit?

 

Any help much appreciated!

Link to comment
https://forums.phpfreaks.com/topic/254807-test-if-string-ends-in-number/
Share on other sites

Still regular expressions.  :P

$str = 'ghi-jkl-4567-1';

preg_replace('/-[0-9]{1}$/', '', $str);

Why the {1}? You already have the dollar sign to indicate only the end of the string so no repetition criteria is necessary.

 

@John_A: It may not be clear, but with scootstah's replacement solution you do not need to test if there is a -[digit] before trying to remove it. Just run the preg_replace() to remove the -[digit]. If it does not exist it won't be replaced. So, testing for it is a waste of code. For what it's worth, I would use this expression:

$str = preg_replace('/-\d$/', '', $str);

 

The \d is a character class for digit.

 

Still regular expressions.  :P

$str = 'ghi-jkl-4567-1';

preg_replace('/-[0-9]{1}$/', '', $str);

Why the {1}? You already have the dollar sign to indicate only the end of the string so no repetition criteria is necessary.

 

@John_A: It may not be clear, but with scootstah's replacement solution you do not need to test if there is a -[digit] before trying to remove it. Just run the preg_replace() to remove the -[digit]. If it does not exist it won't be replaced. So, testing for it is a waste of code. For what it's worth, I would use this expression:

$str = preg_replace('/-\d$/', '', $str);

 

The \d is a character class for digit.

 

 

My regex is mediocre at best. :P Thanks for the optimization.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.