<?php
/* This function returns the position of string s1 within string s2.
The position is 1 based. If s1 is not in s2, 0 is returned.
*/
function InStr($s1, $s2)
{
//Check for valid input
if(!(is_string($s1) && is_string($s2))) return 0;
$s1len = strlen($s1);
$s2len = strlen($s2);
//Check if s1 in s2 at all
if(!ereg($s1, $s2)) return 0;
//Resolve simple case
if($s1 == $s2) return 1;
//Set initial search limits
$begin = 0;
$end = $s2len - $s1len;
//Initialize position
$position = 0;
//Do binary search of s2 for s1
//Check left side first to find first occurance of s1
//Check right side first to find last occurance of s1
while($end > $begin + 1)
{
$middle = ceil(($begin + $end) / 2);
$leftBegin = $begin;
$rightBegin = $middle + $s1len;
$leftEnd = $middle;
$rightEnd = $end + $s1len;
//Check left first
if(ereg($s1, substr($s2, $leftBegin, $rightBegin - $leftBegin)))
{
$end = $middle;
}
else //(ereg($s1, substr($s2, $leftEnd, $rightEnd - $leftEnd)))
{
$position += $middle - $begin;
$begin = $middle;
}
}
//Resolve 1 off problems introduced by ceil
if(ereg($s1, substr($s2, $end, $s1len))) $position++;
//Return position 1 based
return $position + 1;
}
?>
{ 0 nhận xét... read them below or add one }
Đăng nhận xét