Skip to content

Instantly share code, notes, and snippets.

@joshuaadickerson
Created August 25, 2015 23:40
Show Gist options
  • Save joshuaadickerson/d3bd1ab890afbf4cf9df to your computer and use it in GitHub Desktop.
Save joshuaadickerson/d3bd1ab890afbf4cf9df to your computer and use it in GitHub Desktop.
An insitu (no copy) string comparison comparable to substr_compare()
<?php
function instr($string, $substr, $offset = 0, $length = -1)
{
$pos = (int) $offset;
$substr_pos = 0;
for (; $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 === -1 || $length + 1 === $substr_pos)
{
return true;
}
if (isset($string[$pos]))
{
return false;
}
}
}
return true;
}
$string = 'abcdefghijklmnopqrstuvwxyz';
$substr = 'def';
$offset = 3;
$length = 0;
var_dump(insitu_compare($string, $substr, $offset, $length));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment