Reputation: 1948
I have a list of allowed letters
$allowedLetters = array('B','C','D','F','G','H','J','K','L','M','N','P','R','S','T','V','W','X','Y','Z');
And from that array I would like to do string increment to get the following pattern:
BBB, BBC, BBD ... until ZZZ
I know that I can do string increment as simple as this:
$letters = array();
$letter = 'BBB';
while ($letter !== 'ZZZ') {
$letters[] = $letter++;
}
print_r($letters);
But it will not match my allowed letters list, and I just can not find a way how to either do an increment using allowed list or just exclude letters that I do not want such as:
A,E,I,O,Q,U
What could be more simple? I would appreciate if anyone could assist.
Upvotes: 1
Views: 60
Reputation: 7490
I propose a solution starting from your code that involves strcspn()
function:
$letters = array();
$letter = 'BBB';
while ($letter !== 'ZZZ') {
$letter++;
if(strcspn($letter, "AEIOU") == 3 )
$letters[] = $letter;
}
print_r($letters);
The mentioned function returns the index of the first occurrence of the characters listed in needle
parameter. So, in our case, it will return a value in the range [0-2]
if any of the characters is present. According to the manual page, no one of the characters specified in needle
list is found, the length of the original string is returned (in our scenario it is always equal to 3).
This means that making sure that it returns 3 we are accepting only strings that don't contain the forbidden characters "AEIOU"
, appending them to our output array.
Upvotes: 1