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?
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.
[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.

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.