Skip to content

Instantly share code, notes, and snippets.

@lmatteis
Created July 3, 2012 08:41
Show Gist options
  • Save lmatteis/3038530 to your computer and use it in GitHub Desktop.
Save lmatteis/3038530 to your computer and use it in GitHub Desktop.
Write a simple PHP script that accepts a single word and URL that then returns the number of instances the word is found at the destination URL.
<?php
/**
* This returns the amount of times
* a $word is found in a string ($str)
*/
function wordsInString($word, $str) {
// \b is for a word boundary,
// the i modifier is for case-insensitive matching
// g is for global
$regex = "/\b$word\b/i";
preg_match_all($regex, $str, $matches);
if(count($matches)) {
return count($matches[0]);
}
return 0;
}
/**
* Write a simple PHP script that accepts a single word and URL
* that then returns the number of instances the word is found at the destination URL.
*/
function httpWordFinder($word, $url) {
$res = file_get_contents($url);
if($res) {
return wordsInString($word, $res);
}
return 0;
}
// TESTS
assert(wordsInString('duck', 'duck this ducking duck') == 2);
assert(wordsInString('Great', 'great Great GReAT GReATER') == 3);
assert(httpWordFinder('function.get-magic-quotes-gpc.php', 'http://php.net/manual/en/function.assert.php') == 1);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment