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 {} \;
をメモしておこう…