从字符串中删除最后一个逗号(PHP / Wordpress)
我正在 WordPress 中的自定义帖子类型上生成术语列表,在这段代码中,我在每个项目的末尾添加一个逗号,以列表格式将其分隔开,我如何消除最后一个逗号在加法中的传播或删除列表中的最后一个逗号。
$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;
我尝试了以下方法但没有成功;
<em><?php $string = $catTags;
echo preg_replace("/\,$/","",$catTags); ?></em>
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>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你可以简单地做:
You can do simply:
我通常做的是在循环的开头添加一个逗号,通过检查变量中是否已有数据。
所以在这种情况下是这样的:
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:
这应该有效:
return substr($string, 0, -strlen(','));
将删除字符串末尾的最后一个逗号。
This should work:
return substr($string, 0, -strlen(','));
will remove the last comma at the end of the string.