Jump to content

removing multiple commas with recursion; Someone please help!


discostudio

Recommended Posts

[code]

$string = "Hiil Road, Peterborough, , , , ";

function remove_commas($str) {

if ( substr($str, -2, 2) === ", ")
{
$str = substr($str, 0, -2);
echo $str."<br />";
}
if(substr($str, -2, 2) === ", ")
remove_commas($str);
else
return $str;
}[/code]

In theory the above function should work! - Can someone help?
Link to comment
Share on other sites

As far as I can see, it should work. Maybe change the === operator to ==.
In general, recursion is not really recommended with php. Try using a loop instead (again, replace === with == if it doesn't work and give it a shot):
[code]<?php

function remove_commas($str)
{
while(substr($str, -2, 2) === ", ")
$str = substr($str, 0, -2);
return $str;
}

?>[/code]

Orio.
Link to comment
Share on other sites

[quote author=kenrbnsn link=topic=123408.msg509996#msg509996 date=1169416217]
Why won't using str_replace work?
[code]<?php
$string = "Hiil Road, Peterborough, , , , ";
$new_str = str_replace(', ','',$string);
echo $new_str;
?>[/code]

Ken
[/quote]

Thanks for the reply, but that would remove the , betwen "Hiil Road, Peterborough" and I need that to stay there. The point of this is that I could also have a varibale as follows:

"Hill Road, Peterborough, London, Essex, , , , , , "

I just need to remove the trailing commas. regardless of how many there may be.
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.