Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- $INDEX = array('of'=>'long', 'strings that'=>'should', 'be searched for,'=>'transformed to lower case', 'and'=>'without double spaces'); # the values act as slug names e.g. for articles, the keys are the titles
- $search = 'search string, transformed to lower case and without double spaces';
- $res = array(); # empty array for results
- foreach ($INDEX as $key => $val) {
- $searchptr = 0;
- while (TRUE) {
- $str = $key;
- $i = stripos($str, $search[$searchptr]);
- if ($i === FALSE) {
- break 1;
- } else {
- $str = substr($str, $i+1);
- $i = 1; # now used to count matching letters = recognition length threshold (here at 3 chars)
- if ($i === strlen($search)) {
- if (!array_key_exists($val, $res)) { # sorting slugs only, score = relevance of result
- $res[$val] = 0;
- }
- $res[$val]++;
- }
- $searchptr++;
- while (TRUE) {
- if ($searchptr >= strlen($search)) {
- break 2;
- } elseif (strlen($str) == 0) {
- break 1;
- } elseif ($str[0] !== $search[$searchptr]) {
- /* single mismatch, no score for you! */
- /* these conditions are 1 char fault tolerant */
- if ($str[1] === $search[$searchptr]) {
- # missing char in search
- $str = substr($str, 1);
- } elseif ($str[0] === $search[$searchptr+1]) {
- # missing char in string
- $searchptr += 2;
- } elseif ($str[1] === $search[$searchptr+1]) {
- # char mismatch
- $str = substr($str, 1);
- $searchptr += 2;
- } else {
- /* none of the next chars match; match has ended */
- break 1;
- }
- } else {
- /* another match! */
- $str = substr($str, 1);
- if (++$i > 2 || $i === strlen($search)) {
- if (!array_key_exists($val, $res)) { # sorting slugs only, score = relevance of result
- $res[$val] = 0;
- }
- $res[$val]++;
- }
- $searchptr++;
- }
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement