Regular expression and trailing slash
I have this regular expression in PHP with the preg_match/preg_replace functions:
/test\/([A-Za-z]+)\/([A-Za-z]+)\/?([A-Za-z]+)?\/?/
=>
test/\1_\2/\3/
What I want is, that if it only says http://domain.com/test
then it doesn't matter wheter there is a trailing slash or not - how do I do that?
EDIT:
I am doing this:
I have this array:
$routing = array(
'/test\/([A-Za-z]+)\/([A-Za-z]+)\/?([A-Za-z]+)?\/?/' => 'test/\1_\2/\3/',
'/error\/([0-9]+)/' =&g开发者_如何学编程t; 'error/error_\1',
'/sitemap\.html/' => 'sitemap',
'/search\/([^\/]+)?/' => 'search/view/$1',
);
What I do is, that I perform this action to route the URL:
global $routing;
foreach ( $routing as $pattern => $result ) {
if ( preg_match( $pattern, $url ) ) {
return preg_replace( $pattern, $result, $url );
}
}
return ($url);
My framework is doing this in the routing:
E.g. the url can be test/stack/hello/21 which is = to Test::stack_hello(21)
So the set up is actually: controller/func/tion/parameter = function/func_tion/parameter.
$regex = '#test(?:/([a-z]+))(?:/([a-z]+))(?:/([a-z]+))/?$#i';
This matches a string that contains test, followed by a / and a series of letters, then that pattern is repeated twice more. The last character of the string to match is an optional / (and then the string should end because of the $). The pattern is repeated three times because that's the only way all three matches can be used as replacement patterns.
$text = 'test/abc/de/f';
$replacement = 'test/\1_/\3/\2/'; // de and f should switch places
var_dump(preg_replace($regex, $replacement, $text));
That shows the string test/abc_/f/de/
精彩评论