概要
閲覧数:1279
投稿日:2015-12-12
更新日:2015-12-12
携帯電話番号だけを許可
・0X0-YYYY-ZZZZあるいは0X0YYYYZZZZ
・半角数字だけを許可
・Xは7,8,9の何れか
mixed preg_match($pattern,$string)
・Perl互換正規表現関数の一つ
・文字列$patternで指定したPerl互換正規表現により、文字列$stringを検索する
・具体的には、第2引数の文字列へ対して、第1引数で指定した正規表現のパターンを実行
コード
$mobileTel = '070-3456-7890'; //true
$clean = array();
if ($mobileTel && preg_match("/^0[7-9]0-?[0-9]{4}-?[0-9]{4}$/", $mobileTel)) {
$clean["mobileTel"] = $mobileTel;
}
var_dump($clean);
$mobileTel = '';
$clean = array();
$mobileTel = '071-3456-7890'; //3番目の数字が0ではないためfalse
if ($mobileTel && preg_match("/^0[7-9]0-?[0-9]{4}-?[0-9]{4}$/", $mobileTel)) {
$clean["mobileTel"] = $mobileTel;
}
var_dump($clean);
$mobileTel = '';
$clean = array();
$mobileTel = '07034567890'; //true
if ($mobileTel && preg_match("/^0[7-9]0-?[0-9]{4}-?[0-9]{4}$/", $mobileTel)) {
$clean["mobileTel"] = $mobileTel;
}
var_dump($clean);
$mobileTel = '';
$clean = array();
$mobileTel = '070-3456-789'; //桁数が足りないためfalse
if ($mobileTel && preg_match("/^0[7-9]0-?[0-9]{4}-?[0-9]{4}$/", $mobileTel)) {
$clean["mobileTel"] = $mobileTel;
}
var_dump($clean);
$mobileTel = '';
$clean = array();
$mobileTel = '070-3456-789!'; //半角数字以外のためfalse
if ($mobileTel && preg_match("/^0[7-9]0-?[0-9]{4}-?[0-9]{4}$/", $mobileTel)) {
$clean["mobileTel"] = $mobileTel;
}
var_dump($clean);
結果
array(1) {
["mobileTel"]=>
string(13) "070-3456-7890"
}
array(0) {
}
array(1) {
["mobileTel"]=>
string(11) "07034567890"
}
array(0) {
}
array(0) {
}