0

I am generating a list of the terms on a custom post type in Wordpress, in this code i add a comma to the end of each item to separate it in a list format, how would i either eliminate the last the comma from propagating on addition or remove the last comma on the list.

$terms = get_the_terms( $post->ID, 'clients' );
if ( $terms && ! is_wp_error( $terms ) ) :
$clients_list = array();
foreach ( $terms as $term ) {
    $clients_list[] = $term->name;
}
$clients = join( ", ", $clients_list );
$catTags .= "$clients, ";
endif;

I have tried the following to no success;

<em><?php $string = $catTags;
    echo preg_replace("/\,$/","",$catTags); ?></em>
1

3 Answers 3

5

You can do simply:

rtrim($catTags, ', ');
3
  • 1
    You do need ', ' instead of ',' because you have an extra space at the end of the string. I've just corrected it.
    – Sagi
    Commented Sep 30, 2011 at 8:58
  • thanks, wordpress was generating a space after the , that worked fine thanks ! :D
    – Xavier
    Commented Sep 30, 2011 at 8:58
  • i just realised that and deleted my previous comment haha :D
    – Xavier
    Commented Sep 30, 2011 at 8:59
0

What I usually do, is to add a comma at the begin of a loop, by checking if there is already data in the variable.

So in this case something like this:

if (strlen($catTags) > 0)
    $catTags .= ',';
1
  • So you are calculating the string's length at each iteration? I think it is better to build it with an array, then just join the items with the separator.
    – Sagi
    Commented Sep 30, 2011 at 9:00
0

This should work:

return substr($string, 0, -strlen(','));

will remove the last comma at the end of the string.

Not the answer you're looking for? Browse other questions tagged or ask your own question.