Does each letter in the alphabet in a string at least once?

I wonder if there was a more efficient way to determine if a string contains each letter in the alphabet one or more times using a regular expression?

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; } } } 
+7
php regex
source share
5 answers

With a regex, you can do this, but it is not optimal and does not work at all, @hjpotter, if from much faster:

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

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

  • [^az] matches any letter character
  • (.) captures a letter in group 1
  • (?=.*\1) checks if the same letter is somewhere else (on the right)
  • Modifier i makes case insensitive
+3
source share

Just use array_diff :

 count(array_diff($az, $str)) > 0; 
+5
source share

I have no regular expression. But without a regular expression, you can try using the count_chars function.

For example:

 $test_string = 'abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz'; echo count(count_chars($test_string, 1)); 

Gives you 26 - the number of unique characters from $ test_string with a frequency greater than zero.

+2
source share

The current program will print pangram for all lines with pangram alphabets, which means that even aaa... is a pangram.

In your inner loop, you can simply break if any character from az not found:

 function is_pangram($str) { if (strlen($str) < 26) return false; $az = str_split('abcdefghijklmnopqrstuvwxyz'); for ($az as $char) { if (stripos($str, $char) === false) return false; return true; } } 

A regular expression is not optimal in this situation. An alternative approach would be to use array_map and str_count .

0
source share

Create an array of boolean elements of length 26. Then you can scroll the line only once. In pseudo code (because I don't know PHP):

 Boolean b[26]; // Initialized to false count = 0; Loop for each char c in string if (not b[c]) then ++count; b[c] = true end if (count == 26) break; // All present; end end // If count < 26 then not all present 

You need to figure out how to make the index of characters in the array, but this should not be too complicated.

0
source share

All Articles