I came up with a way to do this without RegEx, however your conditions will still match:
function my_func($str) { $letters = 'abcdefghijklmnopqrstuvwxyz'; $match = true; // Will be set to false if does not match conditions $l1pos = strrpos($letters, $str[0]); $l2pos = strrpos($letters, $str[1]); $l3pos = strrpos($letters, $str[2]); $l4pos = strrpos($letters, $str[3]); $l5pos = strrpos($letters, $str[4]); // If letter 2 comes before letter 1 if ($l2pos < $l1pos) { $match = false;} // If letter 3 comes before letter 2 if ($l3pos < $l2pos) { $match = false; } // If letter 4 comes after letter 3 if ($l4pos >= $l3pos) { $match = false; } // If letter 5 comes after letter 4 if ($l5pos >= $l4pos) { $match = false; } return $match; }
You can use it like this:
$string = 'apple'; if (my_func($string)) { print 'Matched!'; } else { print 'Not Matched. :('; }
If you want to make the function really small, you can use the following:
function my_func($str) { $letters = 'abcdefghijklmnopqrstuvwxyz'; $match = true; function m($i) { return strrpos($letters, $str[$1]); } if ((m(1) < m(0)) || (m(2) < m(1)) || (m(3) >= m(2)) || (m(4) >= m(3))) { $match = false; } return $match; }
I also experimented with RegEx and got the following:
^([az]) # First Letter ([\1-z]) # Second Letter ([\2-z]) # Third Letter ([a-\3]) # Fourth Letter ([a-\4]) # Fifth Letter
However, you cannot use az when dynamically setting a or z to one of the previous captured groups. You can use PHP concatenation to create RegEx, however, this will require at least 4 lines of code for each letter except the first.
source share