Created
October 31, 2012 06:32
-
-
Save jaketoolson/3985444 to your computer and use it in GitHub Desktop.
PHP Code Sample
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Jake Toolson | |
// PHP Code Sample | |
// This illustrates the styles I use and techniques/methods used to problem solve. | |
function words_sort_callback($a, $b) | |
{ | |
if ($b[0] - $a[0]) | |
{ | |
return $k; | |
} | |
return strcmp($b[1], $a[1]); | |
} | |
// Submitted text. | |
$text = 'The duck flew over the pond while in search of other ducks nearby. The ducks in the pond however were decoys and the hunters were nearing.'; | |
// Sanitize the incoming string stripping out tags and additional characters using the FILTER_SANITIZE_STRING filter. | |
// Convert all text to lowercase as requested | |
$text_clean = filter_var(strtolower($text), FILTER_SANITIZE_STRING); | |
// Convert sanitized string to an array based on matched expression requirements (a-z, and 0-9). | |
// Expression can me modified to allow additional charcters | |
// Ignore empty returns with PREG_SPLIT_NO_EMPTY constraint | |
// Convert array to a array( Text => Count ) format | |
$words_array = array_count_values(preg_split('/[^a-z0-9]+/', $text_clean, -1, PREG_SPLIT_NO_EMPTY)); | |
// This could be done using an array_map function, but left it in a method easier to read for some. | |
// Remap the array/key combination to: | |
// Array ( | |
// array ( text ) | |
// array ( count ) | |
foreach ($words_array as $k => $v) | |
{ | |
$words_mapped[] = array($k, $v); | |
} | |
// Push array to sorting callback, sorting by total first. | |
usort($words_mapped,'words_sort_callback'); | |
// original input | |
printf("%s\n", $text); | |
// Final result with word count | |
echo '<pre>'; | |
print_r($words_mapped); | |
echo '</pre>'; | |
// If this were to be imported into a database, using PHP 5's PDO class or a standard database library | |
// found within an MVC framework, you can typically perform inserts by using prepared statements which also | |
// add a layer of "sanitation" at the database insert level. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment