A quick question.
The standard str_replace function looks like this:
mixed str_replace ( mixed needle, mixed str, mixed haystack )
I'd like to turn it into this (in analogy with functions like explode and preg_replace):
mixed str_replace ( mixed needle, mixed str, mixed haystack [, int limit] )
Can't find a native php function that does this. Guess I'll have to create it myself or am I overlooking something?
Limited str_replace
Moderator: General Moderators
- Ollie Saunders
- DevNet Master
- Posts: 3179
- Joined: Tue May 24, 2005 6:01 pm
- Location: UK
Is that a joke?GeertDD wrote:you lose the speed of str_replace
I find 1.4 microseconds difference (P4 3.2Ghz, 1024 RAM) between the two with the code below.
Code: Select all
<?php
microtime(true);
$str = 'the quick brown fox jumps over the lazy dog';
$start = microtime(true);
for($i = 0; $i<1000000; $i++)
str_replace('brown', 'black', $str);
echo round(microtime(true) - $start, 1).' microseconds<br>';
$start = microtime(true);
for($i = 0; $i<1000000; $i++)
preg_replace('/brown/', 'black', $str);
echo round(microtime(true) - $start, 1).' microseconds<br>';
?>- Ollie Saunders
- DevNet Master
- Posts: 3179
- Joined: Tue May 24, 2005 6:01 pm
- Location: UK
bokehman, you'll probably have to preg_quote though as well (make sure you specify the second argument).
GeertDD: worry about any performance problems you have when you have them rather than before. Unless a) you know you will have problems b) you can think of a better way quickly c) you're writing a library or similar. Consider CPU time over programmer time which costs more?
GeertDD: worry about any performance problems you have when you have them rather than before. Unless a) you know you will have problems b) you can think of a better way quickly c) you're writing a library or similar. Consider CPU time over programmer time which costs more?
You're right, both. What am I worrying about? What's worse is that I was even trying to develop my own str_replace_limit function (without the use of preg_functions), just because I thought PCRE was slow.
Well, after benchmarking, my own function seemed to take twice the time of the preg_replace equivalent. Twice! And then the function does not accept arrays yet.
Thanks for the advice guys.
Well, after benchmarking, my own function seemed to take twice the time of the preg_replace equivalent. Twice! And then the function does not accept arrays yet.
Code: Select all
// Beware, bad function, very slow!
function str_replace_limit($needle, $str, $haystack, $limit = 0) {
$limit = max(0, (int) $limit + 1);
if ($limit > 0)
$arr = explode($needle, $haystack, $limit);
else
$arr = explode($needle, $haystack);
$str = implode($str, $arr);
return $str;
}