Created
January 28, 2014 13:14
-
-
Save uzulla/8667383 to your computer and use it in GitHub Desktop.
WAFのRouterなどで、'/test/:hoge/'とか指定してルートを登録するときそれを正規表現にコンパイルするやつ
http://uzulla.hateblo.jp/entry/2014/01/28/215038
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$pattern = '/test/:id/'; | |
$regexPattern = preg_replace_callback( | |
'#:([\w]+)#', | |
function($m){ | |
return '(?P<'.$m[1].'>[^/]+)'; | |
}, | |
$pattern | |
); | |
// 生成された正規表現 | |
var_dump($regexPattern); | |
// string(20) "/test/(?P<id>[^/]+)/" | |
// 実際に入力してマッチさせてみる | |
$input = '/test/hoge/'; | |
$is_match = preg_match("#".$regexPattern."#", $input, $matches); | |
//結果 | |
var_dump($is_match); | |
// int(1) | |
var_dump($matches); | |
// array(3) { | |
// [0] => | |
// string(11) "/test/hoge/" | |
// 'id' => | |
// string(4) "hoge" | |
// [1] => | |
// string(4) "hoge" | |
// } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment