You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 $i characters. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 03:28:17