I have a comma separated string, which consists of a list of tags and want to convert it to array to get a link for every tag.
Example:
$string = \'h
Try this
$tagss = trim($tagss);
return substr($tagss, 0 , strlen($tagss)-1);
The workaround(!) would be to remove the unwanted trailing characters afterwards:
$tagss = rtrim($tagss, ", ");
This rtrim removes any mix of spaces and commas from the right end of the string.
Btw, you could use str_getcsv instead of explode, which also handles input spaces better.
Another solution:
$html = trim(preg_replace('/([^,]+)/', ' <a href="/tags/\1" title="\1">\1</a>', $string));
Or if you have to html encode the tags (always smart, since you're creating html from text):
$html = trim(preg_replace_callback('/([^,]+)/', function($match) {
$tag = $match[1];
return ' <a href="/tags/' . urlencode($tag) . '" title="' . htmlspecialchars($tag) . '">' . htmlspecialchars($tag) . '</a>';
}, $string));
So this $string
would work too: "tag with space,html,css,php,mysql,javascript"
More regex is always good!
Just like you explode
d you can implode again:
$tags = explode(',', $arg);
foreach ($tags as &$tag) {
$tag = '<a href="' . $u . 'tag/' . $tag . '/" title="' . $tag . '">' . $tag . '</a>';
}
return implode(', ', $tags);