0

I have a variable $collectors which can contain from one to seven peoples names separated by semicolons. If the string houses a single name then it will be followed by seven semicolons, if it houses two names then 5 semicolons. How can I strip out the extraneous semicolons that are at the end of the string while leaving the ones separating the actual peoples names in place?

Examples of data held in $collectors John Doe;;;;;;; John Doe;Jane Doe;;;;;; John Doe;Jane Doe;Bob Smith;;;;; etc.

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
QuePID
  • 103
  • 1
  • 9
  • 1
    `$collectors = rtrim($collectors, ';');` - http://www.php.net/manual/en/function.rtrim.php – Mark Baker Oct 02 '14 at 11:15
  • 1
    Whilst you can certainly trim the string, perhaps you should look at how you are generating the variable in the 1st place – Steve Oct 02 '14 at 11:18

2 Answers2

3

If those names can be at every position in the CSV string you can use preg_replace():

$strippedSemicolonStr = preg_replace('/;+/', ';', $str);

Be aware that with this solution it's possible to have a string ending with a ; because it just removes duplicate semicolons.

If all names are at the begining of the CSV string (without gaps) you can use rtrim():

$strippedSemicolonStr = rtrim($str, ';');

With this solution you'll loos any semicolons at the end of the string. So the new string won't end in a ;.

TiMESPLiNTER
  • 5,741
  • 2
  • 28
  • 64
0

You can use the trim function, found in many languages, to remove specified characters from the beginning and end of strings.

$string = 'John Doe;;;;;;;';
$string = trim ( $string, [";"] );

http://php.net/manual/de/function.trim.php

Dendromaniac
  • 378
  • 1
  • 14
Guardian667
  • 417
  • 4
  • 16