Last active
September 15, 2021 11:29
-
-
Save popovserhii/ea725cf05a0b23e4d950d70869227028 to your computer and use it in GitHub Desktop.
Custom implementation of PHP strpos function
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 | |
# 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