Page 1 of 1

str_replace once

Posted: Tue Jul 10, 2007 9:28 am
by superdezign
I'm drawing a blank. I want str_replace to do only run through a string once. preg_replace has the 'limit' parameter, but str_replace does not. I'd like to avoid using preg_replace since I know the exact tring I'd like to replace, but the string can occur more than once.

Posted: Tue Jul 10, 2007 9:41 am
by TheMoose
Just use preg_replace with the exact string and limit param? The pattern can be a pattern with no regex in it :)

Posted: Tue Jul 10, 2007 9:54 am
by Gente
I don't think it's a good idea to use preg_replace() here.
If you want to replace the first fragment you can just write simple function with combination of strpos(), strlen() and substr().
I no you can try to manipulate with explode() and join() :)

Posted: Tue Jul 10, 2007 10:08 am
by superdezign
Gente wrote:I don't think it's a good idea to use preg_replace() here.
If you want to replace the first fragment you can just write simple function with combination of strpos(), strlen() and substr().
I no you can try to manipulate with explode() and join() :)
The reason I was trying to avoid preg_replace was because str_replace is faster, but to go through that many functions sounds like preg_replace would be the better choice.

Posted: Tue Jul 10, 2007 10:35 am
by Jaxolotl
what about substr_replace() http://php.net/substr_replace

Posted: Tue Jul 10, 2007 10:54 am
by superdezign
Jaxolotl wrote:what about substr_replace() http://php.net/substr_replace
I looked into that earlier as well, but it'd require a call to strpos().

Posted: Tue Jul 10, 2007 12:29 pm
by vigge89
superdezign wrote:
Jaxolotl wrote:what about substr_replace() http://php.net/substr_replace
I looked into that earlier as well, but it'd require a call to strpos().
I don't have anything backing me up on this, but shouldn't a substr_replace() combined with strpos() be faster than a preg_replace()-call?

Posted: Tue Jul 10, 2007 1:47 pm
by Jaxolotl
remember strpos() will return the position of the LAST occurence only

Posted: Tue Jul 10, 2007 2:27 pm
by RobertGonzalez
strrpos() finds the last occurence in the string. strpos() finds the first occurence.