7
6

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 5 years have passed since last update.

filter_var関数を使ってIPアドレスかどうかをチェックする

Posted at

概要

以前にIPアドレスかどうかをチェックするPHPスクリプトというのをゴリゴリ書いてみたが、filter_var関数を使ってチェックが可能であるということお教え頂いたので書いてみた。前回同様に処理は"配列内の文字列がIPアドレスであればTrue、そうでなければFalseをechoする"というもの。

コード

tekito.php
<?php

$str = array("1.2.3...4", "1.2.3.4.", "hoge.2.3.4", "1.2.256.4", "1.2.3.4");

foreach($str as $x) {
    if(filter_var($x, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
        echo "True" . PHP_EOL;
    } else {
        echo "False" . PHP_EOL;
    }
}

?>

使用例

上記のtekito.phpをそのまま実行

$ php tekito.php 
False
False
False
False
True

使用した関数

  • filter_var

その他メールアドレスやURLのフィルタリングも出来て便利そう。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?