Page 1 of 1
string operation to replace a character
Posted: Mon Oct 20, 2008 11:29 pm
by susrisha
i have a string that goes like
Code: Select all
$somestring = 'laks:asdasd:hhsah:asdhsau';
I want to replace the character ':' with '-' , so my out put should be
Code: Select all
$converted_string = 'laks-asdasd-hhsah-asdhsau';
how do i do it??
Re: string operation to replace a character
Posted: Mon Oct 20, 2008 11:47 pm
by omniuni
~pickle | Please use [ code=html ], [ code=php ], etc tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:
Posting Code in the Forums to learn how to do it too.
Look at
http://us2.php.net/str_replace
If you want, create a function to do it specifically, something along the lines of
Code: Select all
function replacecolons($mystring){
$mynewstring = str_replace(':', '-', $mystring );
return $mynewstring;
}
//call your function...
$gibberish = 'blahblah:blah';
$gibberish = replacecolons($gibberish);
//$gibberish now is blahblah-blah
I think that should work, although I don't have time to test it at the moment.
-OmniUni
~pickle | Please use [ code=html ], [ code=php ], etc tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:
Posting Code in the Forums to learn how to do it too.
Re: string operation to replace a character
Posted: Mon Oct 20, 2008 11:54 pm
by susrisha
thanks it works..
Re: string operation to replace a character
Posted: Tue Oct 21, 2008 10:15 am
by pickle
Why bother with the extra replacecolons() function? There's no reason not to just call str_replace() directly.
Re: string operation to replace a character
Posted: Fri Oct 24, 2008 1:45 am
by omniuni
It offers flexibility and less typing if you need to expand it later, say, to deal with semicolons as well. It can make code easier to read, by providing a more "English" command than having to interpret each time. If you decide to change what it does, make one change in the function, and it is reflected throughout the program, rather than having to modify every instance of a command.
Re: string operation to replace a character
Posted: Tue Oct 28, 2008 12:34 pm
by pickle
Valid opinion I guess. To me though, it seems like he very specifically wants to just replace colons & adding another function just creates more overhead.
Obviously though, it's up to the original poster.
Re: string operation to replace a character
Posted: Tue Oct 28, 2008 2:01 pm
by omniuni
The overhead is a good point. For me, at least, I try to do reusable code when I can simply because I'm not doing a lot of complicated things yet, and the overhead is far less of a concern to me than the fact that I often change my mind later about how I want to work with X Y or Z.
Re: string operation to replace a character
Posted: Tue Oct 28, 2008 2:44 pm
by pickle
I've got 30+ inter-campus apps running on one server, so I tend (or try to be at least) a bit of an overhead nazi
