Whenever you iterate through a loop and add ,
to the end of the string, the final string will have a ,
on the end of it. To solve this, use implode
on an array, rather than appending stuff to a string.
Example:
<?php
$data = 'foo,bar,oof,rab';
$split = explode(',', $data);
$buffer = '';
foreach ($split as $value) {
$buffer .= $value . ', ';
}
var_dump( $buffer ); // string(20) "foo, bar, oof, rab, "
var_dump( implode(', ', $split)); // string(18) "foo, bar, oof, rab"
DEMO
In your example to also remove empty values, you can simply use preg_split
, array_filter
and implode
:
<?php
$data = 'Word1, Word2, Word3, Word4, Word5,';
// Split on comma and remove empty values
$words = array_filter(preg_split('/\s*,\s*/', $data));
// string(33) "Word1, Word2, Word3, Word4, Word5"
var_dump( implode(', ', $words) );
// string(41) "Word1 OR Word2 OR Word3 OR Word4 OR Word5"
var_dump( implode(' OR ', $words) );
DEMO
Notice that we can glue it together with whatever we choose.
Why use preg_split
instead of explode
? It's simple. preg_split
with a regex of \s*,\s*
will split the string on "any amount of spaces (\s*
)" followed by "a comma (,
)" followed by "any amount of spaces (\s*
)". This means that we can join on eg. .
and get Word1.Word2.Word3.Word4.Word5
rather than Word1. Word2. Word3. Word4. Word5
(so essentially we have full control).