php分裂大数字(如爆炸)

Joh*_*ith 2 php explode

我需要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)

  • 实际上,为什么要使用正则表达式呢? (2认同)
  • 首先,如果您想使用给定基准数字,您需要共享测试.除非我们能够重现结果,否则任意给予结果对我来说绝对没有任何意义.至于差异,是的,它们会变小.但为什么你会使用正则表达式呢?没有模式.有一些功能旨在分割字符串,所以对于有人推荐使用正则表达式引擎,甚至保护它,似乎是不好的建议.这就像说要在屏幕上打印"hello world",你应该使用Zend Framework. (2认同)