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
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.

 

Link to comment
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.

 

 

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

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.