PHPで文字列をスペース埋め、ゼロ埋めする方法
文字列をスペースやゼロで埋めて固定長を作成する方法をご紹介します。
str_pad
文字列を固定長の他の文字列で埋めます。
基本構文
str_spad( 対象文字列, 文字列サイズ [, 埋める文字 [, タイプ]]);
タイプ
STR_PAD_RIGHT | 文字列の右側を埋める(デフォルト) |
STR_PAD_LEFT | 文字列の左側を埋める |
STR_PAD_BOTH | 文字列の両側を埋める |
ゼロ埋め
<?php
print str_pad('123', 5, "0"); //"12300"
print str_pad('123', 5, "0", STR_PAD_LEFT); //"00123"
print str_pad('123', 5, "0", STR_PAD_BOTH); //"01230"
?>
スペース埋め
<?php
print str_pad('abc', 5); //"abc "
print str_pad('abc', 5, " ", STR_PAD_LEFT); //" abc"
print str_pad('abc', 5, " ", STR_PAD_BOTH); //" abc "
?>
sprintf
指定したフォーマットで文字を作成します。
基本構文
sprintf( フォーマット [, 文字列1 [, 文字列2… ]] );% %文字。型指定子の先頭に指定します。
b | 2進数の整数 |
c | ASCII値の文字 |
d | 10進数の整数 |
e | 科学記法(例 1.2e+2) |
E | %eと同様だが大文字を指定 (例 1.2E+2) |
f | double型の浮動小数点数 |
F | float型の浮動小数点数 |
g | %eおよび%fの短縮形 |
G | %Eおよび%fの短縮形 |
o | 8進数の整数 |
s | 文字列 |
u | 符号無し10進数との整数 |
x | 16進数(小文字で)の整数 |
X | 16進数(大文字で)の整数 |
ゼロ埋め
<?php
print sprintf('%05d', 123); //"00123" 右寄せでゼロ埋め
print sprintf('%05s', '123'); //"00123" 右寄せでゼロ埋め
print sprintf('%-05s', '123'); //"12300" 左寄せでゼロ埋め
?>
スペース埋め
<?php
print sprintf('%5s', 'abc'); //" abc" 右寄せでスペース埋め
print sprintf('%5d', 123); //" 123" 右寄せでスペース埋め
print sprintf('%-5s', 'abc'); //"abc " 左寄せでスペース埋め
print sprintf('%-5d', 123); //"123 " 左寄せでスペース埋め
?>
マルチバイト文字
半角カナなどのマルチバイト文字の場合、1文字を3バイトとして判断するため、
下記の場合だと先頭1バイトの空白になります。
<?php
print sprintf('%10s', 'アイウ'); //" アイウ"
?>
-
前の記事
PHPの文字列の長さ(桁数)の取得方法 2020.10.06
-
次の記事
ORCALE SQL Developerで複数のテーブル編集タブを開く方法 2020.10.07
コメントを書く