// Compare string, returns the first region of the two strings with the same character
Static void php_similar_str (const char * txt1, int len1, const char * txt2, int len2, int * pos1, int * pos2, int * max)
{
Char * p, * q;
Char * end1 = (char *) txt1 + len1;
Char * end2 = (char *) txt2 + len2;
Int l;
* Max = 0;
// Traverse strings
For (p = (char *) txt1; p <end1; p ++ ){
For (q = (char *) txt2; q <end2; q ++ ){
For (l = 0; (p + l <end1) & (q + l <end2) & (p [l] = q [l]); l ++ );
If (l> * max ){
// Save the same region information
* Max = l;
* Pos1 = p-txt1;
* Pos2 = q-txt2;
}
}
}
}
// Recursive function, compare the same number of characters of txt1 and txt2
Static int php_similar_char (const char * txt1, int len1, const char * txt2, int len2)
{
Int sum;
Int pos1, pos2, max;
Php_similar_str (txt1, len1, txt2, len2, & pos1, & pos2, & max );
If (sum = max) {// What is the significance of this write ?????!!!!!
// Recursion of the front of the last part
If (pos1 & pos2 ){
Sum + = php_similar_char (txt1, pos1, txt2, pos2 );
}
// Recursion the back of the last part
If (pos1 + max <len1) & (pos2 + max <len2 )){
Sum + = php_similar_char (txt1 + pos1 + max, len1-pos1-max,
Txt2 + pos2 + max, len2-pos2-max );
}
}
// Returns the same number of characters after this comparison.
Return sum;
}
// The PHP function itself, a bunch of macros, implements some string conversion and return value conversion. The main function is implemented by the above two functions.
PHP_FUNCTION (similar_text)
{
Zval ** t1, ** t2, ** percent;
Int ac = ZEND_NUM_ARGS ();
Int sim;
If (ac <2 | ac> 3 | zend_get_parameters_ex (ac, & t1, & t2, & percent) = FAILURE ){
WRONG_PARAM_COUNT;
}
Convert_to_string_ex (t1 );
Convert_to_string_ex (t2 );
If (ac> 2 ){
Convert_to_double_ex (percent );
}
If (Z_STRLEN_PP (t1) + Z_STRLEN_PP (t2) = 0 ){
If (ac> 2 ){
Z_DVAL_PP (percent) = 0;
}
RETURN_LONG (0 );
}
Sim = php_similar_char (Z_STRVAL_PP (t1), Z_STRLEN_PP (t1), Z_STRVAL_PP (t2), Z_STRLEN_PP (t2 ));
If (ac> 2 ){
Z_DVAL_PP (percent) = sim * 200.0/(Z_STRLEN_PP (t1) + Z_STRLEN_PP (t2 ));
}
RETURN_LONG (sim );
}
We can see that similar_text is compared based on ASCII and does not consider the phrase issue.
The test result is as follows:
Int main (int argc, char * argv [])
{
Char * str1 = "weican wuxin ";
Char * str2 = "wuxin weican ";
Int pos1, pos2, max;
Php_similar_str (str1, strlen (str1), str2, strlen (str2), & pos1, & pos2, & max );
Printf ("php_similar_str: % d, % d = % d", pos1, pos2, max );
Max = php_similar_char (str1, strlen (str1), str2, strlen (str2 ));
Printf ("php_similar_char: % d", max );
System ("PAUSE ");
Return 0;
}
Php_similar_str: 0, 6 = 6
Php_similar_char: 6
Char * str1 = "original a mechanism for TCP communication ";
Char * str2 = "TCPa Protocol Communication Working Principle ";
Php_similar_str: 3, 4 = 14
Php_similar_char: 19