How to use SimHashPHP to compare text similarity
masterTo compute a similarity index between two texts, you need to follow three main steps:
- Extract features: Use an extractor (like
SimpleTextExtractor) to process the raw text. - Generate hashes: Use the
SimHashclass to generate a fingerprint (hash) from the extracted features. You can specify the hash size, such as\Tga\SimHash\SimHash::SIMHASH_64. - Compare fingerprints: Use a comparator (like
GaussianComparator) to calculate the similarity index between two fingerprints. The result is typically a value between 0 and 1.
Ensure you include vendor/autoload.php to load the library classes.
<?php
require 'vendor/autoload.php';
$text1 = "Some text content...";
$text2 = "Some similar text content...";
$simhash = new \Tga\SimHash\SimHash();
$extractor = new \Tga\SimHash\Extractor\SimpleTextExtractor();
$comparator = new Tga\SimHash\Comparator\GaussianComparator(3);
// 1. Extract and Hash
$fp1 = $simhash->hash($extractor->extract($text1), \Tga\SimHash\SimHash::SIMHASH_64);
$fp2 = $simhash->hash($extractor->extract($text2), \Tga\SimHash\SimHash::SIMHASH_64);
// 2. View binary representation
var_dump($fp1->getBinary());
var_dump($fp2->getBinary());
// 3. Compare (returns index between 0 and 1)
var_dump($comparator->compare($fp1, $fp2));