Skip to content

Instantly share code, notes, and snippets.

@selfawaresoup
Last active August 29, 2015 14:17
Show Gist options
  • Save selfawaresoup/d4e61ffe03e6509edb68 to your computer and use it in GitHub Desktop.
Save selfawaresoup/d4e61ffe03e6509edb68 to your computer and use it in GitHub Desktop.
script to help detect small typos in text files

Installation

Copy typo.php somewhere in your $PATH and rename it to typo (or whatever you like).

Usage

typo some_file

Example, using it on itself

There are a few comment lines in the script that will show up as results.

$ typo typo.php
"usr" / "use"
 1: #!/usr/bin/env php
51: $show_lines = function($l) use ($line_digits, $lines) {

"fopen" / "fupen"
28: $f = fopen($filepath, "r");
71: // fupen

"strlen" / "strln"
47: $line_digits = strlen($i);
57:         if (strlen($w1) > 2 && !in_array($w2, $visited)) {
72: // strln

"STR_PAD_LEFT" / "STR_PAD_LFT"
52:     echo sprintf('%s: %s', str_pad($l+1, $line_digits, " ", STR_PAD_LEFT), $lines[$l]);
73: // STR_PAD_LFT
#!/usr/bin/env php
<?php
if (count($argv) !== 2) {
echo 'Usage: typo file' . PHP_EOL;
die(1);
}
$filepath = $argv[1];
if (!file_exists($filepath)) {
echo sprintf('%s doesn\'t exist.'.PHP_EOL, $filepath);
die(1);
}
if (!is_file($filepath)) {
echo sprintf('%s is not a file.'.PHP_EOL, $filepath);
die(1);
}
if (!is_readable($filepath)) {
echo sprintf('Can\'t read file %s.'.PHP_EOL, $filepath);
die(1);
}
$words = [];
$lines = [];
$f = fopen($filepath, "r");
$i = 0;
while ($l = fgets($f)) {
$lines[] = $l;
$matches = [];
$n = preg_match_all('@\w+@', $l, $matches);
foreach($matches[0] as $w) {
if (!array_key_exists($w, $words)) {
$words[$w] = [$i];
} else {
$words[$w][] = $i;
}
}
$i++;
}
fclose($f);
$line_digits = strlen($i);
$visited = [];
$show_lines = function($l) use ($line_digits, $lines) {
echo sprintf('%s: %s', str_pad($l+1, $line_digits, " ", STR_PAD_LEFT), $lines[$l]);
};
foreach($words as $w1 => $l1) {
foreach ($words as $w2 => $l2) {
if (strlen($w1) > 2 && !in_array($w2, $visited)) {
$lev = levenshtein($w1, $w2);
if ($lev > 0 && $lev < 2) {
$visited[] = $w1;
echo sprintf('"%s" / "%s"'.PHP_EOL, $w1, $w2);
array_map($show_lines, $l1);
array_map($show_lines, $l2);
echo PHP_EOL;
}
}
}
}
// tests for this script
// fupen
// strln
// STR_PAD_LFT
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment