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