Reputation: 27
I would like to match a sequence of letters in a string. For instance if I have the letters T B E I want to match all strings that starts with the letter T and contains the letters B and E at least once. The second letter has to appear before the third, and there might be an infinite number of characters between the letters.
That is the letters T B E would match the strings Table, Trouble and Terrible but not Teb.
I'm trying to code this in php by using
$A = 'T';
$B = 'B';
$C = 'E';
$matches = preg_grep('/^'.$A.'.+'.$B.'.+'.$C.'/', $words);
where words is an array containing a list of words. With my way the algorithm works, but I'm not able to find words where there are no letters in between $A $B or $C.
How would I use regular expressions to fix this?
Upvotes: 0
Views: 2617
Reputation: 32797
The reason you are not able to find words where there are no letters in between $A $B or $C is because you are using .+
which is trying to match atleast 1 character between $A $B or $C.
Use .*
instead of .+
Upvotes: 1