正規表現考える
<?php $str = "/content/hoge/fuga/piyo/ドメイン/hoge.html"; $regular1 = "/\/content\/(.*?)\/(.*?)\/(.*?)\//"; //[/content/hoge/fuga/piyo/] $regular2 = "/^\/([^\/]*\/){4}/"; //[/content/hoge/fuga/piyo/] $regular3 = "/^\/((.*?)\/){4}/"; //[/content/hoge/fuga/piyo/] preg_match($regular1, $str, $matches1); preg_match($regular2, $str, $matches2); preg_match($regular3, $str, $matches3); echo "元: ".$str.PHP_EOL; echo PHP_EOL; echo "正規表現: ".$regular1.PHP_EOL; echo "パターン全体にマッチしたテキスト: ".$matches1[0]; echo PHP_EOL; echo PHP_EOL; echo PHP_EOL; echo "正規表現: ".$regular2.PHP_EOL; echo "パターン全体にマッチしたテキスト: ".$matches2[0]; echo PHP_EOL; echo PHP_EOL; echo PHP_EOL; echo "正規表現: ".$regular3.PHP_EOL; echo "パターン全体にマッチしたテキスト: ".$matches3[0]; echo PHP_EOL; echo PHP_EOL;
パターンマッチを確認
matches
matches を指定した場合、検索結果が代入されます。 $matches[0] にはパターン全体にマッチしたテキストが代入され、 $matches[1] には 1 番目のキャプチャ用サブパターンにマッチした 文字列が代入され、といったようになります。
1. 正規表現: /\/content\/(.?)\/(.?)\/(.*?)\//
Array ( [0] => /content/hoge/fuga/piyo/ [1] => hoge [2] => fuga [3] => piyo )
2. 正規表現: /^\/([^\/]*\/){4}/
Array ( [0] => /content/hoge/fuga/piyo/ [1] => piyo/ )
3. 正規表現: /^\/((.*?)\/){4}/
Array ( [0] => /content/hoge/fuga/piyo/ [1] => piyo/ [2] => piyo )