Remove the last Comma from a string (PHP / Wordpress)

匿名 (未验证) 提交于 2019-12-03 02:41:02

问题:

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:

You can do simply:

rtrim($catTags, ', '); 


回答2:

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 .= ','; 


回答3:

This should work:

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

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



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!