Skip to content

Instantly share code, notes, and snippets.

@popovserhii
Last active September 15, 2021 11:29
Show Gist options
  • Save popovserhii/ea725cf05a0b23e4d950d70869227028 to your computer and use it in GitHub Desktop.
Save popovserhii/ea725cf05a0b23e4d950d70869227028 to your computer and use it in GitHub Desktop.
Custom implementation of PHP strpos function
<?php
# Live Codding https://codeshare.io/
# Task
Find the position of the first occurrence of a substring in a string
strpos ( string $haystack , string $needle [, int $offset = 0 ] ) : int | false
fucntion strpos(string $haystack, string $needle, int $offset = 0): int|false
{
}
# ----
# Solution
function strPosition($haystack, $needle, $offset = 0)
{
$count = strLength($needle);
$countHaystack = strLength($haystack);
if ($offset < 0) {
return false;
}
$start = false;
for ($i = 0; $i < $count; $i++) {
$innerCount = 0;
for ($o = $offset; $o < $countHaystack; $o++) {
$symbol = $needle[$i];
$hSymbol = $haystack[$o];
if ($symbol === $hSymbol) {
$i++;
$start = $o;
$innerCount++;
if ($innerCount === $count) {
break 2;
}
} else {
$start = false;
}
}
}
if ($start !== false) {
$start = $start - ($count - 1);
}
return $start;
}
function strLength($string)
{
$i = 0;
while (true) {
if (isset($string[$i])) {
$i++;
} else {
break;
}
}
return $i;
}
var_dump(strPosition('/api/controller/action/api', 'api', 0));
var_dump(strpos('/api/controller/action/api', 'api', 0));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment