PHP中提取字符串第2-5位字符并存入数组的方法
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

