0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

PHPビルトイン関数~固定長のデータを扱う~

Posted at

学習記録

#前提条件
・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;
//結果 : **-****-****
0
0
0

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?