Regular expression for searching letters before or after a certain letter

I have the following array in PHP:

$words = array("apple", "banana", "lemon"); 

I want to find a word in which it matches the following profile:

  • The first letter can be any az
  • The second letter must be the same letter as after the first letter (i.e. if the first letter is p , the second letter must be p or after it in the alphabet)
  • The third letter must be the same letter as after the second letter
  • The fourth letter must be before the third letter
  • The fifth letter must be up to the fourth letter

Is there a way to create a regex that can meet the above conditions? That would be better since I also want to create an implementation in MySQL, so regular expressions will be more portable for the new situation.

+6
source share
1 answer

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.

+6
source

All Articles