0

Trying to get a list of all substrings currently I have a function but it's not fully complete. Im using minimum char of 4. What would be a good approach to complement this:

Im also need to find words like "predict", how can this be done best and fastest?

Output

Word:      predictions
Substring: predictions
Substring: redictions
Substring: edictions
Substring: dictions
Substring: ictions
Substring: ctions
Substring: tions
Substring: ions
Rubytastic
  • 15,001
  • 18
  • 87
  • 175
  • 1
    Do these need to be actual words? Also, passing `100` to `substr()` in this case is unnecessary. [RTFM](http://php.net/substr) – Jason McCreary Jun 21 '12 at 22:03
  • @Jason No they don't need actual words your right on the 100, that should be the string length of the longest word that's being feed to the function. – Rubytastic Jun 21 '12 at 22:08
  • possible duplicate of [How to find all substrings of a string in PHP](http://stackoverflow.com/questions/2099732/how-to-find-all-substrings-of-a-string-in-php) – Emil Vikström Jun 21 '12 at 22:12
  • No. If you read the manual, it should not be passed at all in your case. See my answer. – Jason McCreary Jun 21 '12 at 22:13

1 Answers1

1

The following will create a substring trimming from the right and left of the word down to length of 4 in the same loop. That was the specification I understood.

$length = strlen($word) - 4;
for ($i = 1; $i <= $length; ++$i) {
    echo "left = ", substr($word, $i), PHP_EOL;
    echo "right = ", substr($word, 0, -$i), PHP_EOL;
}

Assumption: By words you mean substrings.

Note: I also added the logic for a minimum length of 4 characters as well as micro-optimized the for loop (static limit and pre-increment counter).

Jason McCreary
  • 71,546
  • 23
  • 135
  • 174