简体   繁体   English

PHP Regex用于重写404脚本中的部分URL

[英]PHP Regex for rewriting part of URL in 404 script

I have a php script handling URL's that are about to be redirected to 404. 我有一个处理URL的PHP​​脚本,该URL将被重定向到404。

How can I rewrite an URL like example.com/oldnonexistentcategory-actualproduct- product_reviews-actualproduct.htm to example.com/ product_reviews-actualproduct.htm ? 我怎么可以重写URL一个像example.com/oldnonexistentcategory-actualproduct- product_reviews-actualproduct.htm到example.com/ product_reviews,actualproduct.htm?

Said another way - how do I remove everything between "example.com/" and "product_reviews" ? 换句话说,如何删除“ example.com/”和“ product_reviews”之间的所有内容?

The only consistent part of the URL is that it contains example.com and product_reviews. URL唯一一致的部分是它包含example.com和product_reviews。 I've considered using preg_match/preg_replace but I'm very new at regex syntax. 我已经考虑过使用preg_match / preg_replace,但是我对regex语法还是很陌生。

If all your URL are based like that, don't use preg_match but explode which is faster and easier to use : 如果您所有的URL都是基于这样的,则不要使用preg_match,而使用explode则更快更容易:

<?php

// ...

$explodedUrl = explode('-', 'oldnonexistentcategory-actualproduct-product_reviews-actualproduct.htm');

$redirectUrl = $explodedUrl[2].'-'.$explodedUrl[3];

echo $redirectUrl; // product_reviews-actualproduct.htm

But be careful, this suppose 2 things : 但是要小心,这假设两件事:

  1. Your URL are always based on 4 parts, separated by "-": " string-string-string-string.htm " 您的网址始终基于4个部分,以“-”分隔:“ string-string-string-string.htm
  2. A part of the slug " string " can't have a "-" char (Otherwise, the script will not work corretly). 子弹“ string ”的一部分不能有“-”字符(否则,脚本将无法正确运行)。

So make sure you don't have a slug with "-" char in a part , not like that : old-non-existent-category-actual-product-product-reviews-actual-product.htm 因此,请确保您没有部分带有“-”字符的子弹 ,而不是这样: old-non-existent-category-actual-product-product-reviews-actual-product.htm

If your URL can have more or less than 4 parts, and you always want the 2 last parts, you can make your script dynamic, it's easy : 如果您的URL可以包含多于或少于4个部分,并且您始终希望最后2个部分,则可以使脚本动态化,这很容易:

$numberPart = count($explodedUrl);
$redirectUrl = $explodedUrl[$numberPart - 2].'-'.$explodedUrl[$numberPart - 1];

EDIT: 编辑:

Can I use explode to remove everything between / and product_reviews? 我可以使用explode删除/和product_reviews之间的所有内容吗?

Absolutely ! 绝对!

$explodedUrl = explode('product_reviews-', 'oldnonexistentcategory-actualproduct-product_reviews-actualproduct.htm');
$redirectUrl = $explodedUrl[count($explodedUrl) - 1]; // Get string after "product_reviews-"
echo $redirectUrl; // actualproduct.htm

// So finally :
echo "example.com/product_reviews-".$redirectUrl; // example.com/product_reviews-actualproduct.htm

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM