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
4
  • 1
    Do these need to be actual words? Also, passing 100 to substr() in this case is unnecessary. RTFM Commented Jun 21, 2012 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. Commented Jun 21, 2012 at 22:08
  • possible duplicate of How to find all substrings of a string in PHP Commented Jun 21, 2012 at 22:12
  • No. If you read the manual, it should not be passed at all in your case. See my answer. Commented Jun 21, 2012 at 22:13

1 Answer 1

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).

Sign up to request clarification or add additional context in comments.

2 Comments

Thnks that totally did it, smart way of doing it although I don't know if I fully get the for ($i = 1; $i <= $length; ++$i) { line
See the update and let me know if you still have a question about the for loop.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.