php,explode関数
explode関数の使い方です。
文字列を特定の文字で区切ってその配列を返す関数です。
では、構文です。
array explode ( string $delimiter , string $string [, int $limit ] )
- string $delimiter
- 文字列を区切るための文字列
- string $string
- 対象となる文字列
- int $delimiter
- 対象文字列の区切る数を示す
では、サンプルコードです。
<?php
$keyword = "one,two,three,four,five";
//キーワードを分割する
print_r(explode(",",$keyword));
?>
実行結果
Array(
[0] => one
[1] => two
[2] => three
[3] => four
[4] => five
)
$keywordは一つの文字列でしたが、explode関数によって,で分割されました。
explodeの返り値はarrayなので、変数に代入することもできます。
explodeのリミット値
第3引数のlimitに関してです。
実際にサンプルコードをみると良くわかります。
<?php
$keyword = "one,two,three";
//キーワードを分割する
print_r(explode(",",$keyword,1));
print_r(explode(",",$keyword,2));
print_r(explode(",",$keyword,3));
print_r(explode(",",$keyword,-1));
?>
実行結果
Array ( [0] => one,two,three )
Array ( [0] => one [1] => two,three )
Array ( [0] => one [1] => two [2] => three )
Array ( [0] => one [1] => two )
第3引数は対象文字列の分割数を表しています。
-を引数につけると最後の要素を除いた要素がArrayとして返されます。