Teiv
Teiv

Reputation: 2635

Finding words contain non-duplicated specific letters?

I have a list of English words and I want to find out which words have specific letters and those letters must be used once only. I'm using PHP.

So if the letters are 'abcde' then the words should be like 'cab', 'bed'... but not 'dad'. My current attempt is

if (preg_match("/([abcde]+)/i", $w))
    echo $w, "\r\n";

But this just lists all the words contain one of those letters 'abcde'. So can anybody tell me how to do it?

Upvotes: 3

Views: 460

Answers (2)

hsz
hsz

Reputation: 152206

You can try with:

$letters     = str_split('abcde');
$wordLetters = str_split($w);

if ( count(array_intersect($letters, $wordLetters)) == count($wordLetters) ) {
  echo $w, "\r\n";
}

Upvotes: 1

Mark Baker
Mark Baker

Reputation: 212412

To Identify if each $word contains only letters from the $letters string, without duplication

$letters = 'abcde';

$words = array(
    'cab',
    'bed',
    'dad'
);

foreach($words as $word) {
    $valid = testWord($word, $letters);
    echo $word, ' => ', (($valid) ? 'Yes' : 'No'), PHP_EOL;
}

function testWord($word, $letters)
{
    $kChars = array_intersect(
        str_split($letters),
        str_split($word)
    );

    return count($kChars) == strlen($word);
}

Upvotes: 1

Related Questions