[知恵袋を覗いていたら、書いてみたいコードがあったが、回答を書き込んでしまって質問を閉じられると、他の人のコードも見れないには嫌だなと思ったので、こちらにしれっと書いてみる。](http://qiita.com/ShibuyaKosuke/items/296a9007da4336d97848)
token_get_allを使ってみたくて、関数を書いてみました。
細かくテストしてないので、バグがあったら教えてください( ´ ▽ ` )ノ
ちなみにstackoverflowでも似たような質問がありました。
[Matching braces puzzle](http://stackoverflow.com/questions/18527972/matching-braces-puzzle)
```:PHP
<?php
/**
* check matching of braces
*
* @param string $src target string to check
* @return bool
*/
function brace_check($src)
{
$open_braces = str_split("({[");
$close_braces = str_split(")}]");
$braces = array_merge($open_braces, $close_braces);
// PHP open tagが含まれていないなら追加する
$tokens = token_get_all($src);
$open_tag_found = false;
array_walk_recursive( $tokens, function($item,$key){
$open_tag_found |= $key === 0 && in_array($item,[T_OPEN_TAG,T_OPEN_TAG_WITH_ECHO]);
});
if ( !$open_tag_found ){
// PHPコードとして処理
$tokens = token_get_all('<?php '.$src);
}
// bracesを含むであろう文字列トークン以外は捨てる
$tokens = array_filter($tokens,function($item){ return is_string($item); });
$open_brace_stack = array();
foreach($tokens as $key => $t){
if (in_array($t,$open_braces)){
// 開括弧なら開括弧スタックに乗せる
array_push( $open_brace_stack, $t);
}
elseif (in_array($t,$close_braces)){
if ( empty($open_brace_stack) ){
// 開括弧スタックが空ならエラー
return false;
}
// 括弧の対応を確認(開括弧スタックのトップと現在の文字)
$open_top = array_pop($open_brace_stack);
$idx_open = array_search($open_top, $open_braces);
$idx_close = array_search($t, $close_braces);
if ( $idx_open !== $idx_close ){
return false;
}
}
}
return true;
}
//=========================
// test code
$html_case = <<<HTML
<?php
?>
<html>
...
<ul>
<li>1)...</li>
<li>2)...</li>
</ul>
...
<?php
...
?>
...
</html>
HTML;
$expressions = array(")(){}","[]({})","([])","{()[]}","([)]",$html_case);
var_dump(array_map('brace_check', $expressions));
```
- Output for 5.4.0 - 5.4.41, 5.5.24 - 5.5.25, 5.6.8 - 5.6.9
- Parse error: syntax error, unexpected '`' in /in/0HJbc on line 83
Process exited with code 255. - Output for 5.3.0 - 5.3.29
- Parse error: syntax error, unexpected '[' in /in/0HJbc on line 28
Process exited with code 255. - Output for 4.4.2 - 4.4.9, 5.1.0 - 5.1.6, 5.2.0 - 5.2.17
- Parse error: syntax error, unexpected T_FUNCTION in /in/0HJbc on line 27
Process exited with code 255. - Output for 4.3.0 - 4.3.1, 4.3.5 - 4.3.11, 4.4.0 - 4.4.1, 5.0.0 - 5.0.5
- Parse error: parse error, unexpected T_FUNCTION in /in/0HJbc on line 27
Process exited with code 255. - Output for 4.3.2 - 4.3.4
- Parse error: parse error in /in/0HJbc on line 27
Process exited with code 255.
preferences:
243.26 ms | 1395 KiB | 135 Q