homepage Welcome to WebmasterWorld Guest from 54.234.126.92
register, login, search, subscribe, help, library, PubCon, announcements, recent posts, open posts,
Pubcon Website
Visit PubCon.com
Home / Forums Index / Code, Content, and Presentation / PHP Server Side Scripting
Forum Library : Charter : Moderators: coopster & eelixduppy & jatar k

PHP Server Side Scripting Forum

    
Linking items in a string - and removing trailing comma
abbeyvet




msg:3787523
 10:39 pm on Nov 16, 2008 (gmt 0)

I can do either, but not both together, and there must be a way!

I have created a tagging system, the tags are entered as a comma separated list, and I currently retrieve and display the tags like so:

$query = "SELECT pTags FROM tablename WHERE pID = whatever";
$result = mysql_query ($query);
$row = mysql_fetch_array($result);
$list = $row[0];
$tags = explode(',', $list);
foreach ($tags AS $tags)
{
echo "<a href=\"/tags.php?tag=$tags\">$tags</a>, ";
}

Which works fine, except of course I have a trailing comma and space.

I know I can print them out if I just needed the (unlinked) list using

$tags = substr($list, 0, -2);
echo $tags;

But how can I do both?

 

dreamcatcher




msg:3787544
 11:25 pm on Nov 16, 2008 (gmt 0)

Hi abbeyvet,

A couple of ways you can do this. Firstly, concatenate the vars and use substr_replace [us2.php.net]


$tagData = '';
foreach ($tags AS $tags)
{
$tagData .= "<a href=\"/tags.php?tag=$tags\">$tags</a>, ";
}
echo substr_replace($tagData, '', -2);

Or you can use a count to increment when looping and only add the comma if its not the last entry:


$count = 0;
foreach ($tags AS $tags)
{
echo "<a href=\"/tags.php?tag=$tags\">$tags</a>";
echo (++$count!=count($tags) ? ', ' : '');
}

dc

abbeyvet




msg:3787551
 12:16 am on Nov 17, 2008 (gmt 0)

Thank you VERY much!

I used the first option, it works perfectly!

Global Options:
 top home search open messages active posts  
 

Home / Forums Index / Code, Content, and Presentation / PHP Server Side Scripting
rss feed

All trademarks and copyrights held by respective owners. Member comments are owned by the poster.
Terms of Service ¦ Privacy Policy ¦ Report Problem ¦ About
WebmasterWorld ® and PubCon ® are a Registered Trademarks of Pubcon Inc.
© Pubcon Inc. 1996-2012 all rights reserved