LoginSignup
8
7

More than 5 years have passed since last update.

改行を含む文字列を配列へ

Posted at
対象文字列
$str = "a
b

c

d
e
"

って感じの文字列を

処理結果
array(5) {
  [0]=>
  string(1) "a"
  [1]=>
  string(1) "b"
  [2]=>
  string(1) "c"
  [3]=>
  string(1) "d"
  [4]=>
  string(1) "e"
}

に変換するコード

コード
// 改行コード \r、\n、\r\n の3種を区別せず配列化
$arr = preg_split("/\R/", $str);
// 各要素の空白除去
array_walk_recursive($arr, 'trim');
// 文字列長が0の要素を除去
$arr = array_filter($arr, 'strlen');
// インデックスを振り直す
$arr = array_merge($arr);
8
7
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
7