admin管理员组文章数量:1315251
I am trying to combine two preg_match patterns separate with ,|,.
/blog\/page\/[0-9]+\/?$/ with /tag\/ skip in /blog/page/ and /tag/
/page\/[0-9]+\/?$/ with /[0-9]+\/?$/ ex. /page/2/ and only /2/
/(page\/[0-9]+\/?)$/ with /([0-9]+\/?)$/
function redirect_pagination() {
if(!preg_match('/blog\/page\/[0-9]+\/?$/,|,/tag\/', $_SERVER['REQUEST_URI'])) {
if(preg_match('/page\/[0-9]+\/?$/,|,/[0-9]+\/?$/', $_SERVER['REQUEST_URI'])) {
$new_url = preg_replace('/(page\/[0-9]+\/?)$/,|,/([0-9]+\/?)$/', '', $_SERVER['REQUEST_URI']);
wp_redirect($new_url, 301);
exit;
}
}
}
add_action( 'init', 'redirect_pagination', 1 );
I am trying to combine two preg_match patterns separate with ,|,.
/blog\/page\/[0-9]+\/?$/ with /tag\/ skip in /blog/page/ and /tag/
/page\/[0-9]+\/?$/ with /[0-9]+\/?$/ ex. /page/2/ and only /2/
/(page\/[0-9]+\/?)$/ with /([0-9]+\/?)$/
function redirect_pagination() {
if(!preg_match('/blog\/page\/[0-9]+\/?$/,|,/tag\/', $_SERVER['REQUEST_URI'])) {
if(preg_match('/page\/[0-9]+\/?$/,|,/[0-9]+\/?$/', $_SERVER['REQUEST_URI'])) {
$new_url = preg_replace('/(page\/[0-9]+\/?)$/,|,/([0-9]+\/?)$/', '', $_SERVER['REQUEST_URI']);
wp_redirect($new_url, 301);
exit;
}
}
}
add_action( 'init', 'redirect_pagination', 1 );
Share
Improve this question
asked May 25, 2019 at 7:08
tw8sw8dw8tw8sw8dw8
733 silver badges10 bronze badges
2
- what do you want to do? – user134414 Commented May 25, 2019 at 16:26
- I want to redirect pages such as /post-name/page/2/, /post-name/2/ to /post-name/ except for /blog/page/ and /tag/. I do this with two functions, but I know it is possible with just one. – tw8sw8dw8 Commented May 25, 2019 at 16:55
1 Answer
Reset to default 1I think this is what you are looking for
if (preg_match('@^/((?!blog|tag)[^/]+)/(?:page/)?\d+@', $_SERVER['REQUEST_URI'], $m)) {
wp_redirect("/$m[1]", 301);
}
The regexp uses lookahead to make sure that the first match isn't blog or tag.
The '[^/]+'
part matches anything that isn't a forward slash (/
).
(?:page/)?
- Makes an optional match against 'page/'
\d+
- Match against any number.
This will not redirect '/blog/2
if you want '/blog/2'
to be redirected but not '/blog/page/2'
then change the regexp above to read 'blog/page'
where it now says 'blog'
.
PS: I know this is 5 months old and you have probably moved on by now but I'll put this here anyway in case someone else needs help with the same issue.
本文标签: regexphp pregmatch with multiple patterns
版权声明:本文标题:regex - php preg_match with multiple patterns 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741980899a2408389.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论