Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is every letter in the alphabet in a string at least once?

Tags:

regex

php

Was wondering if there was a more efficient way to detect if a string contains every letter in the alphabet one or more times using regex?

I appreciate any suggestions

$str = str_split(strtolower('We promptly judged antique ivory buckles for the next prize'));

$az = str_split('abcdefghijklmnopqrstuvwxyz');

$count = 0;
foreach($az as $alph) {
    foreach($str as $z) {
        if($alph == $z) {
           $count++;
            break;
        }
    }
}
like image 654
AnchovyLegend Avatar asked May 15 '17 16:05

AnchovyLegend


Video Answer


2 Answers

Just use array_diff:

count(array_diff($az, $str)) > 0;
like image 186
Alex Blex Avatar answered Oct 05 '22 23:10

Alex Blex


With regex you can do that, but it isn't optimal nor fast at all, @hjpotter way if from far faster:

var_dump(strlen(preg_replace('~[^a-z]|(.)(?=.*\1)~i', '', $str)) == 26);

It removes all non letter characters, all duplicate letters (case insensitive), and compares the string length with 26.

  • [^a-z] matches any non letter character
  • (.) captures a letter in group 1
  • (?=.*\1) checks if the same letter is somewhere else (on the right)
  • the i modifier makes the pattern case insensitive
like image 44
Casimir et Hippolyte Avatar answered Oct 06 '22 00:10

Casimir et Hippolyte