How to remove special character from string?

How to remove last character from a string inside a loop

  • I am trying to print the different category's selected in a single line in xml, like <cat_name>meeting, food and drinks, sports</cat_name> The output I am getting: <cat_name>meeting, food and drinks, sports,</cat_name> I want to remove only the last comma. The code I have written so far is: $sq=" select category_main.cat_name from category_main join category on(category.cat_id=category_main.cat_id) where category.event_id='$event_id' "; $e=mysql_query($sq); $xml ='<cat_name>'; while($row=mysql_fetch_array($e)) { $res=$row['cat_name']; //$new = substr($val,0,-1); $xml .="$res, "; } $xml .='</cat_name>'; echo $xml;

  • Answer:

    Call http://us.php.net/manual/function.trim.php with the optional second parameter as a ',' trim($cat_name, ',') However, since you're doing this in a while loop, you should build an array then implode() it rather than building the string in the loop. This avoids the extra comma to begin with. $arr = array(); while($row=mysql_fetch_array($e)) { $arr[] = $row['cat_name']; } $cat_name = implode(",", $arr); // $cat_name is now "meeting, food and drinks, sports"

nithin Kumar at Stack Overflow Visit the source

Was this solution helpful to you?

Other answers

You can do this by [i used my variable] $str = substr($str,0, (strlen($str)-1));

Sonal Khunt

Or use a rtrim, rtrim( $cat , ',' ) http://php.net/rtrim

Andrey Knupp

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.