1
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]入力値がSJISで表現できるか調べる

Posted at

概要

ある文字列がSJISで表現できるかどうかを調べます。

手順

デフォルトの文字コードで表現された文字列を、SJISに変換して再度元の文字コードに変換。
その結果が同一であればSJISで表現できる文字列。(表現できない場合は変換時に?などで置き換えられる為)

結果

<?php
// デフォルト文字コードをUTF-8とする
// SJISで表現できない文字
$a = '𠮟';
var_dump($a);
# => string(4) "𠮟" //問題なく出力される

// UTF-8からSJISに変換
$converted = mb_convert_encoding($a, 'SJIS', 'UTF-8');
var_dump($converted);
# => string(1) "?" //表現されない

// SJISからUTF-8に変換 
$new_a = mb_convert_encoding($converted, 'UTF-8', 'SJIS');
var_dump($new_a);
# => string(1) "?" //表現されない

// $a !== $new_a なので"𠮟"はSJISで表現できない

まとめ

この辺の関数を使用してもうまくチェックできなかったので、今回のような方法を取りました。

何か他に良い方法があったりしたら教えていただけるとありがたいです。

1
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
1
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?