php PHP将字符串转换为数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3279202/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP convert string to array
提问by Richard Knop
How can I convert a string to an array? For instance, I have this string:
如何将字符串转换为数组?例如,我有这个字符串:
$str = 'abcdef';
And I want to get:
我想得到:
array(6) {
[0]=>
string(1) "a"
[1]=>
string(1) "b"
[2]=>
string(1) "c"
[3]=>
string(1) "d"
[4]=>
string(1) "e"
[5]=>
string(1) "f"
}
回答by robertbasic
回答by svarlitskiy
You can loop through your string and return each character or a set of characters using substr in php. Below is a simple loop.
您可以遍历字符串并使用 php 中的 substr 返回每个字符或一组字符。下面是一个简单的循环。
$str = 'abcdef';
$arr = Array();
for($i=0;$i<strlen($str);$i++){
$arr[$i] = substr($str,$i,1);
}
/*
OUTPUT:
$arr[0] = 'a';
$arr[1] = 'b';
$arr[2] = 'c';
$arr[3] = 'd';
$arr[4] = 'e';
$arr[5] = 'f';
*/
回答by radiatedDogsInFukushima
Every String is an Array in PHP
PHP中的每个字符串都是一个数组
So simply do
所以简单地做
$str = 'abcdef';
echo $str[0].$str[1].$str[2]; // -> abc
回答by Phil Hilton
Note that starting with php 5.5 you can refer to string characters by array indices, which in most cases prevents need for the solution(s) above.
请注意,从 php 5.5 开始,您可以通过数组索引引用字符串字符,这在大多数情况下不需要上述解决方案。
$str = 'abdefg';
echo $str[4]; // output: e
回答by Dave
Other solution:
其他解决方案:
$string = 'abcdef';
$arr = [];
for($i=0;$i<strlen($string);$i++){
$arr[] = substr($string,$i,1);
}
回答by Raj Raj
<?php
$str = "Hello Friend";
$arr1 = str_split($str);
$arr2 = str_split($str, 3);
print_r($arr1);
echo "<br/>";
print_r($arr2);
?>

