I want to use grep in PHP in an anagram search. I have a wordlist with 600.000 lines of single words (German words).
Now I want to input 7 letters (e.g. ABCDEFG), make all 5040 permutations with them (its 7!) and feed each mostly senseless anagram possibility (e.g. ABCDEFG, ABCDEGF, ABCDGEF, ...) into grep, to check if that word is in my list.
I run it on a Ubuntu 22.04 server with 16 GB RAM, PHP 8.0 and Apache 2.4.
Is it the best way to add all 5040 anagrams as patterns? E.g.:
shell_exec( 'grep "^ABCDEFG$\|^ABCDEGF$\|..." /path/to/wordlist.txt');
Is that good practice? Or would it be better to use a for next loop with 5040 single grep calls and always only one pattern?
I read that grep could take as many patterns as I want but I didn't find any code where there would be as many patterns as in my approach. I guess the maximum is limited by server capabilities but I didn't test that yet. I don't want to slow down the server too much.
Or is my approach not that good at all and best practice would be totally different?
I tried to use sqlite and used the wordlist in a sqlite DB (with OR for each word) but this takes much too long, it's not possible.
Thanks for hints.
grep
togrep
togrep
… Find a pattern that matches 7-letter words. Find a pattern that matches words with the first letter of the set. Find a pattern that matches words with the second letter of the set… Letters that must appear more than once require special treatment. For a 7-letter word there will be at most 8 patterns, I think.grep -E '^[ABCDEFG]{7}$'
and then filter out entries with duplicate letters.shell_exec()
can be extremely dangerous when run with user-supplied arguments....never trust data supplied by users.