LoginSignup
7
7

More than 5 years have passed since last update.

知恵袋を覗いていたら、書いてみたいコードがあったが、回答を書き込んでしまって質問を閉じられると、他の人のコードも見れないのは嫌だなと思ったので、こちらにしれっと書いてみる。

Last updated at Posted at 2015-05-30

phpのプログラムで
( ) { } [ ] のような括弧があって
これの順番が正しいかどうか判定する関数か何か
を作りたいのですがうまくききません。。

( { [ { ] } } ) 例えばこのような時エラーがでるような
感じです
よろしくお願いします。

で、ざっくり書いてみたのがこれ。

<?php

/**
 * braceCheck
 */
class braceCheck
{

    private $_code = null;
    private $_startBrace = array('(', '{', '[');
    private $_endBrace = array(')', '}', ']');
    private $_braceArr = array();

    /**
     * ソースコードを設定する
     * @param type $string
     * @return \common\braceCheck
     */
    public function setCode($string)
    {
        $this->_code = $string;
        return $this;
    }

    /**
     * コメントを取り除く
     * @todo
     */
    public function removeComment()
    {
        $this->_code = $this->_code;
        return $this;
    }

    /**
     * 文字列中の括弧を取り除く
     * @todo
     * @return \common\braceCheck
     */
    public function removeString()
    {
        $this->_code = $this->_code;
        return $this;
    }

    /**
     * 括弧を探査する
     */
    public function searchBrace()
    {
        $brace = array_merge($this->_startBrace, $this->_endBrace);
        $pattern = sprintf("/[%s]/", preg_quote(implode($brace)));
        preg_match_all($pattern, $this->_code, $matches, PREG_OFFSET_CAPTURE);
        $this->_braceArr = $matches;
        return $this;
    }

    /**
     * シンタックスをチェックする
     */
    public function check()
    {
        try {
            $tmpArr = array();
            foreach ($this->_braceArr[0] as $i => $brace) {
                $index = array_search($brace[0], $this->_endBrace);
                if (is_integer($index) && 0 <= $index) {
                    if ($this->_startBrace[$index] === end($tmpArr)) {
                        array_pop($tmpArr);
                    } else {
                        $msg = "Unexpected {$brace[0]}: {$i}";
                        throw new \Exception($msg);
                    }
                } else {
                    $tmpArr[] = $brace[0];
                }
            }
            if (0 === count($tmpArr)) {
                echo "success\n";
            }
        } catch (\Exception $e) {
            var_dump($e->getMessage());
        }
    }

}

自作でこんなコードを作るくらいなら、

find ./ -name "*.php" -exec php -l {} \;

をメモしておこう…

7
7
5

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
7