我需要php explode()的功能,但没有分隔符.
例如,将变量"12345"转换为数组,单独保存每个数字.
这可能吗?我已经谷歌搜索但只发现爆炸(),似乎没有用.
谢谢!
小智 7
与PHP中的任何字符串:
$foo="12345";
echo $foo[0];//1
echo $foo[1];//2
//etc
Run Code Online (Sandbox Code Playgroud)
或者(来自手册中的preg_split())页面
$str = 'string';
$chars = preg_split('//', $str, -1, PREG_SPLIT_NO_EMPTY);
print_r($chars);
Run Code Online (Sandbox Code Playgroud)
更好的:
$str = 'string';
$chars=str_split($str, 1)
print_r($chars);
Run Code Online (Sandbox Code Playgroud)
preg_split()与str_split()的基准
function microtime_float()
{
list($usec, $sec) = explode(" ", microtime());
return ((float)$usec + (float)$sec);
}
$str = '12345';
$time_start = microtime_float();
for ($i = 0; $i <100000; $i++) {
$chars = preg_split('//', $str, -1, PREG_SPLIT_NO_EMPTY);
//$chars=str_split($str, 1);
}
$time_end = microtime_float();
$time = $time_end - $time_start;
echo "$time seconds\n";
Run Code Online (Sandbox Code Playgroud)
结果:
str_split =0.69
preg_split =0.9
Run Code Online (Sandbox Code Playgroud)