Rated an average of 4 stars by 1 person

Determine Pronounceability of a Word

Script Details:
Added on December 19, 2010 by Zhay. Last modified December 19, 2010.
Zhay accreditted the script to "Andrew Moore <http://stackoverflow.com/users/26210/andrew-moore>."

Description:
This script determines how pronounceable a word is as a percentage (returns values from 0 to 1).

Tags: determine, measure, pronounce, pronounceability, pronounceable, word

Instructions:
Do something like:

<?
$iw = isPronounceable($_GET['word']);

if ($iw > 0.5)
{
echo stripslashes($_GET['word']) . ' can be pronounced.';
}
else
{
echo stripslashes($_GET['word']) . ' can't be easily pronounced.';
}
?>

Code:

<?php
# Snippet from PHP Share: http://www.phpshare.org

function isPronounceable($word)
{
    static 
$vowels = array('a''e''i''o''u''y');
    static 
$composites = array('mm''ll''th''ing');
    
    if (!
is_string($word))
    {
        return 
false;
    }
    
    
// Remove non letters and put in lowercase
    
$word preg_replace('/[^a-z]/i'''$word);
    
$word strtolower($word);
    
    
// Special case
    
    
if ($word == 'a')
    {
        return 
1;
    }
    
    
$len strlen($word);
    
    
// Let's not parse an empty string
    
    
if ($len == 0)
    {
        return 
0;
    }
    
    
$score 0;
    
$pos 0;
    
    while (
$pos $len)
    {
        
// Check
        
if is allowed composites
        
        
foreach ($composites as $comp)
        {
            
$complen strlen($comp);
            
            if ((
$pos $complen) < $len)
            {
                
$check substr($word$pos$complen);
                
                if (
$check == $comp)
                {
                    
$score += $complen;
                    
$pos += $complen;
                    continue 
2;
                }
            }
        }
        
        
// Is it a vowel ? If so, check
        
if previous wasn't a vowel too . if (in_array($word[$pos], $vowels))
        {
            if (($pos - 1) >= 0 && !in_array($word[$pos - 1], $vowels))
            {
                $score += 1;
                $pos += 1;
                continue;
            }
        }
        
        // Not a vowel, check
        if next one is, or
        if is end of word
        else
        {
            if (($pos + 1) < $len && in_array($word[$pos + 1], $vowels))
            {
                $score += 2;
                $pos += 2;
                continue;
            }
            elseif (($pos + 1) == $len)
            {
                ++$score;
                break;
            }
        }
        
        ++$pos;
    }
    
    return $score / $len;
}
?>

Review this PHP Script:

Rating:

Comments:


Login

User:
Pass:

Register

Not a member? Register today and receive the many free benefits of being a member!

Advertisements