Search code examples
phpstringintegertype-conversionsimilarity

similar_text - string / integer comparing


it's my first post here, so welcome everyone!

I'm trying to write a rule to simply protect my website against flooding by users posting it's content. I decided to use similar_text() function in PHP to compare strings (last added string by user and the one that one is adding at the moment), calculate similarity (%) and if the result is too high (similar in more than 90%) the script will not add a record to database.

Here is what I have:

similar_text($last_record, $new_record, $sim);
$similarity = (int) number_format($sim, 0);

if ($similarity < 90)
{
  // add the record
}
else
{
  // dont add anything
}

The problem is with this: if ($similarity < 90). I format the number and then convert it from string to int value, but the script doesn't care.

When I use quotas it works: if ($similarity < "90"). The question is why script doesn't work when I use the value as an integer value and it works when I use it as a string?


Solution

  • number_format returns a string where you need an int. So a string comparison to "90" works, but an int comparison fails. You can use int_val to convert to an int.

    Also, I'm wondering if maybe you have something else wrong. I took your code sample and ran it locally, and it seems to work just fine even without swapping (int) for int_val.

    With the following values:

    $last_record = "asdfasdfasdf";
    $new_record = "aasdfasdfasdf";
    

    $similarity is 96 and the greater than section of the if triggers.

    With these values:

    $last_record = "asdfasdfasdf";
    $new_record = "fffdfasdfasdf";
    

    $similarity is 80 and the less than section of the if triggers.