简体   繁体   中英

Compare two strings in php get number of characters that don't match?

Some users like to write post title all in uppercase, which is completely annoying. Instead of asking them to write it again I want to know what percentage of the title they wrote is uppercase so that if they exceed 50% I just apply strtolower.

My idea is to turn their string to lowercase and see how different it is from the original string (3 different characters would mean originally there were 3 uppercase characters):

$title = 'AAAA';
$title2 =  strtolower($title);

How do I compare $title with $title2 to get the number of characters that don't match?

Eg:

$title = 'AAAa'
$title2 = 'aaaa'

$differences = '3';
$title = 'AAAa';
$title2 =  strtolower($title);
$differences = 0;
for ($i=0,$l=strlen($title); $i < $l; $i++) {
  if ($title{$i} !== $title2{$i}) {
    $differences++;
  }
}

You could try levenshtein($title,$title2,1,1000,1000000) . In the resulting number, the units tell you how many letters had to be added, the thousands tell you how many were changed (probably what you want most here) and the millions tell you the number of deleted letters.

With the PHP's native function similar_text() i think you will get exactly what you want. Example of use:

$title = 'AAAa';
$title2 = 'aaaa';

similar_text ( $title , $title2, $percentege );

echo $percentege . '%'; // Output: 25%

You can use it this way too:

echo similar_text ( $title , $title2 ); // Output: 1

The first usage returns the percentual of similarity between the two strings and the second usage returns the quantity of similar characters that the two strings have.

Hope it can help you!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM