PHP入門 文字列関数 文字列を特定の区切り文字で分割する(explode関数)
文字列を特定の区切り文字で分割するには、explode関数を利用します。
構文:explode関数
explode(string $separator , string $string [,int $limit = PHP_INT_MAX]:array
$separator | 区切り文字 |
$string | 分割する文字列 |
$limit | 分割の最大数 |
例:カンマを区切り文字として分割する
<?php
$data = '山田,工藤,田中,花子,玲子';
print_r(explode(',',$data));

例:区切り文字が文字列に含まれない
<?php
$data = '山田,工藤,田中,花子,玲子';
print_r(explode('-',$data));

区切り文字が文字列に含まれない場合、explode関数は元の文字列をそのまま要素1つの配列として返します。
例:引数$limitを指定した場合
<?php
$data = '山田,工藤,田中,花子,玲子';
print_r(explode('-',$data));

explode関数は$limitの指定数を上限に分割処理を行います。最後の要素には、分割さなかったすべての文字列が含まれます。
例:$limitに負数を指定
<?php
$data = '山田,工藤,田中,花子,玲子';
print_r(explode(',',$data,-2));

explode関数は最後の$limit個(絶対値)を除く分割結果を返します。