【问题标题】:Split variable and Store data into an array拆分变量并将数据存储到数组中
【发布时间】:2017-07-30 13:37:10
【问题描述】:

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

$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]; 
}

它不工作?

【问题讨论】:

  • 只需explode(' ', $cp),它就会为您提供一系列单词。
  • 你的预期输出是什么?

标签: php split


【解决方案1】:
<?php
  $cp="my name is abcd";
  $Words = explode(' ', $cp);

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

$Words 是逐步存储值的数组

【讨论】:

    【解决方案2】:

    由于 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

    【讨论】:

      【解决方案3】:

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

      <?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

      【讨论】:

        【解决方案4】:

        只需使用explode()

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

        输出:

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

        【讨论】:

          猜你喜欢
          • 2012-08-26
          • 1970-01-01
          • 1970-01-01
          • 2014-06-11
          • 2022-07-08
          • 2022-10-13
          • 1970-01-01
          • 2018-10-06
          • 1970-01-01
          相关资源
          最近更新 更多