Last active
December 14, 2015 18:29
-
-
Save alecgorge/5130170 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function mb_str_replace($search, $replace, $subject) { | |
if(is_array($subject)) { | |
$ret = array(); | |
foreach($subject as $key => $val) { | |
$ret[$key] = mb_str_replace($search, $replace, $val); | |
} | |
return $ret; | |
} | |
foreach((array) $search as $key => $s) { | |
if($s == '') { | |
continue; | |
} | |
$r = !is_array($replace) ? $replace : (array_key_exists($key, $replace) ? $replace[$key] : ''); | |
$pos = mb_strpos($subject, $s); | |
while($pos !== false) { | |
$subject = mb_substr($subject, 0, $pos) . $r . mb_substr($subject, $pos + mb_strlen($s)); | |
$pos = mb_strpos($subject, $s, $pos + mb_strlen($r)); | |
} | |
} | |
return $subject; | |
} | |
function mb_str_replace2($search, $replace, $subject){ | |
return preg_replace('@'.preg_quote($search).'@u',$replace,$subject); | |
} | |
$iteration = 100000; | |
$length = array(); | |
$timestart = microtime(true); | |
for($i = 0; $i < $iteration; $i++) { | |
} | |
$length[] = microtime(true) - $timestart; | |
$timestart = microtime(true); | |
for($i = 0; $i < $iteration; $i++) { | |
mb_str_replace("dog", "steak", "The quick dog dog dog dog dog dog dog dog dog dog brown fox jumps over the lazy dog."); | |
} | |
$length[] = microtime(true) - $timestart; | |
$timestart = microtime(true); | |
for($i = 0; $i < $iteration; $i++) { | |
mb_str_replace2("dog", "steak", "The quick dog dog dog dog dog dog dog dog dog dog brown fox jumps over the lazy dog."); | |
} | |
$length[] = microtime(true) - $timestart; | |
var_dump($length); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
pal-nat184-097-113:Downloads alecgorge$ php -f test.php | |
array(3) { | |
[0]=> | |
float(0.0053048133850098) | |
[1]=> | |
float(4.1349000930786) | |
[2]=> | |
float(0.31121706962585) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment