Tag Archives: words

Which words have the letter P in it and what’s the percentage?

Another code snippet from the useless dept, this time for PHP. If you’ve ever written a post and wondered how many words use the letter P (or any character), here’s something for you in PHP:

function find_words_with_letters($letter, $str) {

	$a = preg_split("#[ \n\r]+#", $str);

	$letterupper = strtoupper($letter);
	$letterlower = strtolower($letter);

	$result = array();
	$result['word_count'] = count($a);
	$result['words_with_letter'] = array();

	foreach($a as $i) {
		if (strpos($i, $letterlower) !== false || strpos($i, $letterupper) !== false) {
			$result['words_with_letter'][] = $i;
	$result['words_with_letter_ratio'] = count($result['words_with_letter']) / count($a);

	return $result;

// use it
print_r(find_words_with_letters('p', 'This message has one P'));

By the way, 17.3% of this post have P’s in it!