3

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?

Teiv
  • 2,605
  • 10
  • 39
  • 48
  • Your best bet would probably be to specify the "matches" argument in the preg_match function, and check the array for duplicate results. I found a somewhat similar problem to yours, which relies solely on regex using negative lookahead: http://stackoverflow.com/questions/2631468/regex-to-use-each-letter-only-once – Kippie Jan 17 '13 at 11:03

2 Answers2

1

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);
}
Mark Baker
  • 209,507
  • 32
  • 346
  • 385
  • Not a single Regex is used but it still works like a charm! Thank you guys so much. – Teiv Jan 17 '13 at 11:18
1

You can try with:

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

if ( count(array_intersect($letters, $wordLetters)) == count($wordLetters) ) {
  echo $w, "\r\n";
}
hsz
  • 148,279
  • 62
  • 259
  • 315