-
-
Save live627/40e6a93ebdb13d758420569dfd4e4f9b to your computer and use it in GitHub Desktop.
An insitu (no copy) string comparison comparable to substr_compare()
This file contains 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 instr(string $string, string $substr, int $offset = 0, int $length = null): bool | |
{ | |
for ($pos = $offset, $substr_pos = 0; $pos !== $length; $pos++, $substr_pos++) | |
{ | |
if (isset($substr[$substr_pos])) | |
{ | |
if (isset($string[$pos])) | |
{ | |
if ($string[$pos] !== $substr[$substr_pos]) | |
return false; | |
} | |
else | |
return false; | |
} | |
else | |
{ | |
if ($length === null || $length + 1 === $substr_pos) | |
return true; | |
if (isset($string[$pos])) | |
return false; | |
} | |
} | |
return true; | |
} | |
function test($haystack, $needle) { | |
$repetitions = 0; | |
$start = microtime(true); | |
do { | |
strpos($haystack, $needle); | |
$repetitions += 1; | |
} while (microtime(true) - $start < 5); | |
$rate = round($repetitions / (microtime(true) - $start)); | |
$rate = str_pad($rate, 8, ' ', STR_PAD_LEFT); | |
echo "$rate / second\n"; | |
$repetitions = 0; | |
$start = microtime(true); | |
do { | |
instr($haystack, $needle); | |
$repetitions += 1; | |
} while (microtime(true) - $start < 5); | |
$rate = round($repetitions / (microtime(true) - $start)); | |
$rate = str_pad($rate, 8, ' ', STR_PAD_LEFT); | |
echo "$rate / second\n\n"; | |
} | |
// Worst case | |
test(str_repeat('A', 1e+7) . 'BB', 'BB'); | |
test(str_repeat('aA', 1e+6) . 'aB', 'aB'); | |
test(str_repeat('A', 1e+1) . 'BB', 'BB'); | |
test(str_repeat('aA', 1e+1) . 'aB', 'aB'); | |
// Best case | |
test(str_repeat('a', 1e+7), 'aa'); | |
test(str_repeat('aa', 1e+6), 'aa'); | |
test(str_repeat('a', 1e+1), 'aa'); | |
test(str_repeat('aA', 1e+1), 'aa'); | |
$string = 'abcdefghijklmnopqrstuvwxyz'; | |
$substr = 'def'; | |
$offset = 3; | |
$length = 0; | |
var_dump(instr($string, $substr, $offset, $length)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
11th Gen Intel(R) Core(TM) i7-11700F @ 2.50GHz