PHP preg_splitメソッドでスラッシュで文字列を区切るサンプル
環境
PHP 8.1.2
Ubuntu 22.04.1 LTS
構文
array preg_split ( string $正規表現のパターン , string $入力文字列 [, int $数値 = -1 [, int $flags = 0 ]] )
正規表現で文字列を分割します。
戻り値は配列です。
3つ目の引数(数値)は、分割する数を指定します。省略可能です。0と-1は制限が無いことを意味します。
使用例
<!DOCTYPE html>
<html>
<body>
<?php
$strA = "2022/11/28";
$arrayA = preg_split("/\//",$strA);
echo "<pre>";
print_r($arrayA);
echo "</pre>";
foreach ($arrayA as $str){
echo "<pre>";
echo $str;
echo "</pre>";
}
echo $arrayA[0];
?>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<?php
$strA = "2022/11/28";
$arrayA = preg_split("/\//",$strA);
echo "<pre>";
print_r($arrayA);
echo "</pre>";
foreach ($arrayA as $str){
echo "<pre>";
echo $str;
echo "</pre>";
}
echo $arrayA[0];
?>
</body>
</html>
<!DOCTYPE html> <html> <body> <?php $strA = "2022/11/28"; $arrayA = preg_split("/\//",$strA); echo "<pre>"; print_r($arrayA); echo "</pre>"; foreach ($arrayA as $str){ echo "<pre>"; echo $str; echo "</pre>"; } echo $arrayA[0]; ?> </body> </html>
実行結果
Array
(
[0] => 2022
[1] => 11
[2] => 28
)
2022
11
28
2022
Array
(
[0] => 2022
[1] => 11
[2] => 28
)
2022
11
28
2022
Array ( [0] => 2022 [1] => 11 [2] => 28 ) 2022 11 28 2022