Shortening PHP string to maximum length but erasing last comma set if necessarry

I am storing multiple ID's in a MySQL text field .. for example:

$s='1,3,4,54523,284';

If I use for example

echo mb_strimwidth($s, 0, 7, NULL);

I don't want 1,3,4,5 to be returned but 1,3,4 as "5" is not a valid ID so I'd rather not have it at all

Also, they're may only be a single ID (no comma's at all) -- In this case it should return null as it won't have the space to store the ID #.

Please advise, thanks.
MarkProgrammerAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Julian HansenCommented:
Why is 5 not valid
If you are storing 1,3,4,54523,284 why do you only want 1,3,4 - what criteria determines this.
Why not split the string on commas

$ids = explode(',',$s);

You now have an array of id's you can work with?
0
Julian HansenCommented:
I think I understand. Try this
<?php
define('MAX',7);
$s='1';
$len = strlen($s);
if ($len > MAX) {
  $offset = -(strlen($s) - MAX);
  $index = strrpos($s,',', $offset); 
  if ($index > 0) {
    $s = substr($s,0, $index);
  }
}
echo $s;

Open in new window

0
Julian HansenCommented:
Using mb_strings and slightly more elegant
<?php
define('MAX',7);
$s='1,3,4,54523,284';
$len = mb_strlen($s);
if ($len > MAX) {
  while($s[--$len] != ',');
  $s = mb_substr($s, 0, $len);
}
echo $s;

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
MarkProgrammerAuthor Commented:
Thank you. As for why 5 is not valid, I am storing ID numbers from a different table and therefore can't have mistakes because I couldn't store the full number
0
Julian HansenCommented:
You are welcome.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
PHP

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.