2012-06-30 30 views
0

我想這些URL轉換爲搜索引擎友好的URL:正則表達式是需要改變URL

index.php?t=1&s=1&offset=50&hits=50 ---> index-t-1-s-1-offset-50-hits-50.html 
index.php?t=1&s=1      ---> index-t-1-s-1.html 
index.php?t=1&s=&offset=50&hits=50 ---> index-t-1-s-1-offset-50-hits-50.html 
index.php?t=1       ---> index-t-1.html 

我寫了這個:

$filename = substr(basename($base_href),0,'-4'); 
$str = preg_replace('/href=\'\?t=(\d+)&s=(\d+)\'/i', 'href=\''.$filename.'-t-$1-s-$2.html\'', $str); 

,但我需要一個通用的表達。你能幫我嗎?

回答

1

我注意到你替換.php??我認爲是可選的)term和所有符號爲-,最後追加.html。所以,你只需要做到這一點:

$filename = "index.php?t=1&s=1&offset=50&hits=50"; 
$result = preg_replace('/(?:\.php\??|\W)/', '-', $filename) . '.html'; 
//~> index-t-1-s-1-offset-50-hits-50.html 

它會做:

  • 更換.php?.php-;
  • 將非字母\W(不與\w混淆)替換爲-;
  • 追加.html的結果

瞭解更多關於正則表達式here

+0

看看這裏:http://codepad.org/8JIsK1J0 –

0

對於溶液,還是先通過?拆分URL,然後全部更換&=-,並連接所有的字符串返回(處理後的URL中的另一部分除去.php