如何在不使用explode函数的情况下将字符串转换为php中的数组

时间:2014-08-14 07:34:24

标签: php

我想在不使用php中的explode函数的情况下将字符串转换为数组    我希望输出像( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 )这样但不使用explode()。

    <?php

     $str="this is string"; 

    ?>

应该像这样arr[0]=this arr[1]=is arr[2]=string

6 个答案:

答案 0 :(得分:1)

$j = mb_strlen($theString);
for ($k = 0; $k < $j; $k++) 
{
    $char = mb_substr($theString, $k, 1);
    $var_arr[$k] =  $char;
}

上面的代码不使用任何模式来分割字符串。

一次吸引一个角色

EDIT suppose you have string

$s = 12.3.4.09.20

it will give the array as

array = ('1','2','.','3','.','4','.','0','9','.','2','0');

编辑:完整代码

<?php
$theString = "1.2.34.87";
$var_arr = array();
$j = mb_strlen($theString);
for ($k = 0; $k < $j; $k++) 
{
    $char = mb_substr($theString, $k, 1);
    $var_arr[$k] =  $char;
}
print_r($var_arr);
?>

转到http://phpfiddle.org/并在那里进行测试

检查图像作为证据 enter image description here

enter image description here

答案 1 :(得分:0)

我希望你的模式如下“这是字符串” 因此下面的代码可以用于相同的代码:

<?php
// split the phrase by any number of commas or space characters,
// which include " ", \r, \t, \n and \f
$keywords = preg_split("/ /", "this is string");
print_r($keywords);
?>

由于 毕晓普

答案 2 :(得分:0)

我为此的解决方案...

$string = 'This-is-the-string';
$word = '';$warray = array();

for($i=0; $i<strlen($string);$i++){
    if($string[$i]=='-'){$warray[] = $word;$word = '';}
    else $word .= $string[$i];
}

if($word!='')$warray[] = $word;//Last word;

echo "<pre>";print_r($warray);die;

输出

Array
(
    [0] => This
    [1] => is
    [2] => the
    [3] => string
)

答案 3 :(得分:0)

    $theString = "this is string";
    $var_arr = array();
    $j = mb_strlen($theString);
    $chars = "";
    for ($k = 0; $k < $j; $k++) 
    {

        $char = mb_substr($theString, $k, 1);
        if($char == " ")
        {
            $var_arr[] =  $chars;
            $chars = "";
        }
        else{
            $chars .= $char;
        }

        if( ($k + 1) == $j)
        {
            $var_arr[] =  $chars;
        }

    }
    print_r($var_arr);

答案 4 :(得分:0)

tightly bound under O(n * m^2)

答案 5 :(得分:0)

isdigit

输出: 数组 ( [0] =>此 [1] =>是 [2] => a [3] =>字符串 )