php 将字符串转换为字符数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2768314/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 07:38:19  来源:igfitidea点击:

Convert a String into an Array of Characters

phparraysstring

提问by AJ.

In PHP, how do I convert:

在 PHP 中,我如何转换:

$result = abdcef;

into an array that's:

变成一个数组:

$result[0] = a;
$result[1] = b;
$result[2] = c;
$result[3] = d;

回答by dusk

You will want to use str_split().

您将需要使用 str_split()。

$result = str_split('abcdef');

http://us2.php.net/manual/en/function.str-split.php

http://us2.php.net/manual/en/function.str-split.php

回答by BT643

Don't know if you're aware of this already, but you may not need to do anything (depending on what you're trying to do).

不知道您是否已经意识到这一点,但您可能不需要做任何事情(取决于您要做什么)。

$string = "abcdef";
echo $string[1];
//Outputs "b"

So you can access it like an array without any faffing if you just need something simple.

因此,如果您只需要一些简单的东西,就可以像数组一样访问它而无需任何处理。

回答by Chaim

You can use the str_split() function:

您可以使用 str_split() 函数:

$value = "abcdef";
$array = str_split($value);

If you wish to divide the string into array values of different amounts you can specify the second parameter:

如果您希望将字符串分成不同数量的数组值,您可以指定第二个参数:

$array = str_split($value, 2);

The above will split your string into an array in chunks of two.

以上将您的字符串分成两个块的数组。

回答by Gazler

$result = "abcdef";
$result = str_split($result);

There is also an optional parameter on the str_split function to split into chunks of x characters.

str_split 函数还有一个可选参数,用于拆分为 x 字符块。

回答by Pratik

With the help of str_split function, you will do it.

在 str_split 函数的帮助下,你会做到的。

Like below::

如下图:

<?php 
$result = str_split('abcdef',1);
echo "<pre>";
print_r($result);
?>

回答by Nazca

You can use the str_split()function

您可以使用该str_split()功能

$array = str_split($string);

foreach ($array as $p){

    echo $p . "<br />";
}

回答by Gautam Rai

best you should go for "str_split()", if there is need to manual Or basic programming,

最好你应该选择“ str_split()”,如果需要手动或基本编程,

    $string = "abcdef";
    $resultArr = [];
    $strLength = strlen($string);
    for ($i = 0; $i < $strLength; $i++) {
        $resultArr[$i] = $string[$i];
    }
    print_r($resultArr);

Output:

输出:

Array
(
    [0] => a
    [1] => b
    [2] => c
    [3] => d
    [4] => e
    [5] => f
)