学習記録
#前提条件
・PHP version 5.4
#固定長データを扱う関数
・substr
・substr_replace
・preg_match
・preg_replace
##substr
文字列の一部分を切り返す
書式
$変数=substr(文字列, 抜き出したい最初の位置, 抜き出したい桁数);
//抜き出したい桁数を負にすると文字列の後ろから始まる
builtin.php
$input = '20200422 Item-A 1200';
$date = substr($input, 0, 8);
echo $data;
//結果 : 20200422
##substr_replace
文字列の置換
書式
$変数=strpos(文字列, 置換文字列, 抜き出したい最初の位置, 抜き出したい桁数);
builtin.php
$input = '20200422 Item-A 1200';
echo substr_replace($input, 'Item-B', 8, 8);
//結果 : 20200422Item-B 1200
##preg_match
文字列からある文字列を抜き出して配列にする
書式
preg_match(検索したい文字列, 文字列, 検索結果が代入される);
builtin.php
$input = 'Call at 01-2345-6789 or 10-1112-1214';
$pattern = '/\d{2}-\d{4}-\d{4}/';
preg_match($pattern, $input, $matches);
print_r(($matches);
//結果 : Array ( [0] => 03-3001-1256 )
//allをつければすべて配列にはいる
preg_match_all($pattern, $input, $matches);
print_r($matches);
//結果 : Array ( [0] => Array (
// [0] => 03-3001-1256
// [1] => 03-3015-3222 ) )
##preg_replace
文字列からある文字列を置換する
書式
preg_replace(検索する文字列, 置換したい文字列, 文字列);
builtin.php
$input = 'Call at 01-2345-6789';
$pattern = '/\d{2}-\d{4}-\d{4}/';
$input = preg_match($pattern, '**-****-****', $input);
echo $input;
//結果 : **-****-****