拆分变量并将数据存储到数组中

时间:2017-07-30 13:37:11

标签: php split

我想将拆分数据存储在这样的数组中:

$cp="my name is abcd";
$i=0;
$length=str_word_count($cp);
foreach ($cp as $c ) {
$array[i]=$c;
$i++; 
}
for($j=0;$j<$length;$j++){
echo $array[j]; 
}

它不起作用?

4 个答案:

答案 0 :(得分:0)

<?php
  $cp="my name is abcd";
  $Words = explode(' ', $cp);

  foreach ($Words as $word) {
    echo "$word <br>";            
  }
?>

$ Words是逐步存储值的数组

答案 1 :(得分:0)

由于OP要求逐个抓取每个单词,这里有一个方法,它使用strpos在循环中查找空格和子串的位置。
我使用trim()来删除字符串中的空格,因为$ pos是空格的位置。

$cp="my name is abcd";
$arr = array();
$pos=0;

While(strpos($cp, " ", $pos+1) != ""){// Keep going as long as there is spaces left in string
    $arr[] = trim(substr($cp, $pos, strpos($cp, " ", $pos+1)-$pos));
    $pos = strpos($cp, " ", $pos+1); //next space position
}

$arr[] = substr($cp, $pos+1); //catch the last one after loop +1 because POS is the space position.
Var_dump($arr);

https://3v4l.org/uJdIc

答案 2 :(得分:0)

我不确定你真正需要什么,但可能这段代码可以帮助你:

<?php

$cp="my name is abcd";

// words
$words=explode(' ',$cp);
print_r($words);

// letters
$letters=str_split($cp);
print_r($letters);

您可以在这里测试它们:http://sandbox.onlinephpfunctions.com/code/728a283ba45118fef21cbb215a7424b293682018

答案 3 :(得分:-1)

只需使用explode()

<?php
$cp="my name is abcd";
$arrayOfWords = explode(' ', $cp);
print_r($arrayOfWords);
?>

输出:

Array ( [0] => my [1] => name [2] => is [3] => abcd )