I have a function that reads my tags from wordpress and prints them out,
$posttags = get_the_tags();
if($posttags) {
foreach($posttags as $tag) {
echo $tag->name . ',';
}
}
Now the function gives me a print that looks like this
Tag1,Tag2,Tag3,
So I tried to use the mb_substring
function to remove the last ,
$comma = ",";
$posttags = get_the_tags();
if ($posttags) {
foreach($posttags as $tag) {
echo $tag->name . mb_substr($comma,0, -1) ;
}
}
The problem is that now instead of removing the last comma the print gets like this TagTagTag
Any ideas how to manipulate the script so only the last comma gets removed?
Do it properly and you won't need extra steps. How about:
$posttags = implode(',', get_the_tags());
Or:
if($posttags = get_the_tags()) {
$posttags = implode(',', $posttags);
}
Use rtrim()
:
$no_last_comma = rtrim($string_with_commas, ',');
Why not use substr() to remove last character?
$no_last_comma = substr($string_with_commas, 0, -1);