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

PHP中提取字符串第2-5位字符并存入数组的方法

解决PHP提取指定位置字符并存入数组的问题

Hey there! Let's sort out this issue for you. The problem with your original str_split approach is that the second argument sets the chunk size for splitting the entire string, not the range of characters you want to extract.

Since you need the 2nd to 5th characters (note: PHP uses 0-based indexing for strings, so these correspond to positions 1 to 4), here are two straightforward ways to get the result you want:

Method 1: Use substr + str_split (Simplest)

First, extract the target substring using substr, then split it into individual characters with str_split:

<?php
$string_name = 'abcdefghijklmnopqrst';
// Extract characters from position 1 (2nd character) to position 4 (5th character)
$target_sub = substr($string_name, 1, 4);
// Split the substring into an array of single characters
$result_array = str_split($target_sub);
print_r($result_array);
?>

This will output:

Array
(
    [0] => b
    [1] => c
    [2] => d
    [3] => e
)

Method 2: Loop through specific indices

If you prefer more explicit control, you can loop through the exact indices you need and build the array manually:

<?php
$string_name = 'abcdefghijklmnopqrst';
$result_array = [];
// Loop from index 1 (2nd char) to index 4 (5th char)
for ($i = 1; $i <= 4; $i++) {
    $result_array[] = $string_name[$i];
}
print_r($result_array);
?>

This gives the same output as the first method.

内容的提问来源于stack exchange,提问作者Smit Saraiya

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 10:27:33