PHP中从左到右按字符组合读取字符串的实现方法
Solution for Generating Left-to-Right Prefix Combinations
Your original code is printing individual characters one by one, but we need to build and output each cumulative prefix as we iterate. Here's how to adjust it to get the desired result:
$string = 'India'; // Loop from 1 to the full length of the string (inclusive) for ($i = 1; $i <= strlen($string); $i++) { // Extract the first $i characters to form the current prefix $prefix = substr($string, 0, $i); // Print each prefix with clean formatting (using <pre> as in your original code) echo '<pre>' . $prefix . '</pre>'; }
How this works:
- We start the loop at 1 instead of 0 because our first prefix is the first 1 character of the string, not an empty substring.
- The
substr($string, 0, $i)function grabs the substring starting at index 0 (the start of the string) and captures the next$icharacters. For each iteration:- When $i=1: returns "I"
- When $i=2: returns "In"
- When $i=3: returns "Ind"
- And so on until $i matches the full length of the string, giving us "India"
Example Output:
I
In
Ind
Indi
India
If you prefer plain text output without <pre> tags, you can swap the echo line for:
echo $prefix . PHP_EOL;
内容的提问来源于stack exchange,提问作者mike1225
相关产品推荐
相关产品推荐

