Cory on 07/15/08

# Statistics

Viewed 121 times
Favorited by 3 user(s)

# Approximate / Fuzzy search base.

/ Published in: PHP  This is a simple base for an approximate search application. You can currently use this to do search's but it, is not very sophisticated, right now anything that is as difference in characters base on the threshold will show up in the result, so with a threshold of 1 "the" would return, "he", "she", "thee", etc. But this is more made for a base for extending with your own capabilities.

Copy this code and paste it in your HTML
`<?php	class FuzzySearch {		public \$string;		public \$search; 		public function __construct(\$string = null) {			if(!empty(\$string)) {				self::SetString(\$string);			}		} 		public function SetString(\$string) {			if(is_string(\$string)) {				\$this->string = \$string;			}		} 		public function SetSearch(\$search) {			if(is_string(\$search)) {				\$this->search = \$search;			}		} 		public function PreformSearch(\$search, \$string = null, \$threshold = 1, \$caseSensitive = false) {			if(empty(\$search) && !empty(\$this->search)) { \$search = \$this->search; }			if(empty(\$string) && !empty(\$this->string)) { \$string = \$this->string; }			\$matches = array(); 			if(isset(\$string) && strlen(\$string) > 0) {				\$words = explode(" ", \$string); 				foreach(\$words as \$word) {					\$stripedWord = self::StripFormatting(\$word); 					if(self::CompareStrings(\$search, \$stripedWord, \$caseSensitive) <= \$threshold) {						\$matches[] = \$stripedWord;					}				}			}			return \$matches;		} 		public function CompareStrings(\$str1, \$str2, \$caseInsensitive = false) {			\$threshold = 0; 			if(\$caseInsensitive) {				\$str1 = strtolower(\$str1);				\$str2 = strtolower(\$str2);			} 			if(strlen(\$str1) != strlen(\$str2)) {				if(strlen(\$str1) > strlen(\$str2)) {					\$threshold = strlen(\$str1) - strlen(\$str2);				}				else if(strlen(\$str2) > strlen(\$str1)) {					\$threshold = strlen(\$str2) - strlen(\$str1);				}			} 			for(\$i = 0; \$i < strlen(\$str1); \$i++) {				if(\$i <= strlen(\$str2) - 1) {					if(\$str1{\$i} != \$str2{\$i}) {						\$threshold++;					}				}			}			return \$threshold;		} 		public function StripFormatting(\$str) {			\$formatting = array( ".", ",", ";", ":", "|", "[", "]", "{", "}", "(", ")", "=", "+",								"!", "@", "#", "\$", "%", "^", "&", "*", "/", "\\", "<", ">", "?"); 			\$str = str_replace(\$formatting, "", \$str);			\$str = trim(\$str);			return \$str;		}	}?>` Subscribe to comments