Skip to content

Instantly share code, notes, and snippets.

@macwinnie
Forked from phpfiddle/fiddle_038149.php
Last active October 22, 2018 20:45
Show Gist options
  • Save macwinnie/bdf7e2d42a1b9521fcdbe138d254f47d to your computer and use it in GitHub Desktop.
Save macwinnie/bdf7e2d42a1b9521fcdbe138d254f47d to your computer and use it in GitHub Desktop.
[ Posted by Martin ] Word analysing in texts
<?php
$analyze = '';
$punctuations = '.:-,;–_?!';
if (isset($_POST['analyze']) and trim($_POST['analyze']) != '') {
$analyze = $_POST['analyze'];
$analyzed = preg_replace( "/\s+/", " ", $analyze );
$len = strlen($analyze);
$pl = strlen($punctuations);
for ($i=0; $i < $pl; $i++) {
$analyzed = str_replace($punctuations[$i], ' ', $analyzed);
}
$words = array_filter(explode(' ', $analyzed));
$wl = [];
foreach ($words as $word) {
$wl[] = strlen($word);
}
$result = [
'count all characters' => $len,
'count all words' => count($words),
'different words' => count(array_unique($words)),
'min wordlength' => min($wl),
'max wordlength' => max($wl),
'average wordlength' => number_format( array_sum($wl) / count($wl), 2, ',', '.'),
];
echo '<pre>' . print_r($result, true) . '</pre>';
}
?>
<!-- Your forms -->
<form action="" method="POST" class="myForm">
<textarea placeholder="Dein Text" name="analyze" style="width: 100%;" rows="10"><?php echo $analyze; ?></textarea>
<input type="submit" id="submit" value="analysieren" />
</form>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment