Jump to content

Trim last values


seran128

Recommended Posts

OK I have my code

that displays a dynamic menu like

item1 | item2 | item3 |

the problem is the last | i need to trim it off

so i should get

item1 | item2 | item3

[code]function getmenu(){
global $connection;

$sql=mysql_query("SELECT * from menu order by sort_order") or die(mysql_error());


$getmenu .= "<table width='100%' border='0'><tr><td><span class='copy'>&nbsp;&nbsp;&nbsp;&nbsp;";

while($row=mysql_fetch_array($sql)) {
$getmenu .= "<a href=javascript:menulink(" . $row['ID'] . ")>" . stripslashes($row['title']) . "&nbsp;|&nbsp;&nbsp;";
}

$getmenu .= "</span></td></table>";


return $getmenu;
}[/code]
Link to comment
https://forums.phpfreaks.com/topic/27277-trim-last-values/
Share on other sites

I dont know if there is a better way but I do it like this:

[code]

$links = "item1 | item2 | item3 |";

substr($links, 0, strlen($links)-2);

[/code]

I'm sure there is an easier way but I just knock of  the last few chacters if you know there will always be 1 or 2 characters after the string.

Link to comment
https://forums.phpfreaks.com/topic/27277-trim-last-values/#findComment-124739
Share on other sites

You can use the [url=http://www.php.net/rtrim]rtrim()[/url] function:
[code]<?php
$str = 'item1 | item2 | item3 |';
$str = rtrim($str,' |');
?>[/code]
or you could build the menu slightly differently:
[code]<?php
function getmenu(){
global $connection;
$sql=mysql_query("SELECT * from menu order by sort_order") or die(mysql_error());
$getmenu = "<table width='100%' border='0'><tr><td><span class='copy'>&nbsp;&nbsp;&nbsp;&nbsp;";
$tmp = array();
while($row=mysql_fetch_assoc($sql)) {
$tmp[] = '<a href="javascript:menulink(' . $row['ID'] . ')">' . stripslashes($row['title']);
}
$getmenu .= "&nbsp;" . implode("&nbsp;|&nbsp;",$tmp) . "&nbsp;";
$getmenu .= "</span></td></table>";
        return($getmenu);
}?>[/code]

Ken
Link to comment
https://forums.phpfreaks.com/topic/27277-trim-last-values/#findComment-124740
Share on other sites

one way...

[code]function getmenu()
{
global $connection;

$sql = mysql_query ( "SELECT * from menu order by sort_order" ) or die ( mysql_error () );

$hold = array ();

while ( $row = mysql_fetch_array ( $sql, MYSQL_ASSOC ) )
{
$hold[] = "<a href='javascript:menulink(" . $row['ID'] . ");'>" . stripslashes ( $row['title'] ) . "</a>";
}

return "<table width='100%' border='0'><tr><td><span class='copy'>&nbsp;&nbsp;" . implode ( '&nbsp;&nbsp;|&nbsp;&nbsp;', $hold ) . "&nbsp;&nbsp;</span></td></table>";
}[/code]


Link to comment
https://forums.phpfreaks.com/topic/27277-trim-last-values/#findComment-124741
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.