2011-12-14 33 views
0

很久以前,我問了幾乎相同的東西,但現在我需要更多更難的東西。我需要同樣的正則表達式的代碼爲所有的請求工作(如果可能的話)需要一個正則表達式來創建友好的URL

所以我們可以說我有以下幾點:

$friendly = ''; to output/
$friendly = '/////'; to output/
$friendly = '///text//'; to output /text/ 
$friendly = '/text/?var=text'; to output /text/ 
$friendly = '/text/?var=text/'; to output /text/var-text/ 
$friendly = '/[email protected]#$%^&*(()_+|/#anchor'; to output /text/ 
$friendly = '/[email protected]#$%^&*(()_+|text/[email protected]#$%^&*(()_+|text/'; to output /text/text/ 

希望有意義!

+0

我不明白 - 你想在.htaccess中? – deviousdodo 2011-12-14 15:03:51

+4

自從你最後一個問題以來,你有沒有試圖學習正則表達式? [man](http://www.php.net/manual/en/reference.pcre.pattern.syntax.php)或[ri](http://regular-expressions.info/) - 只需發佈需求並詢問代碼是無關緊要的。 – mario 2011-12-14 15:06:19

回答

4

看起來像preg_replace(),parse_url()rtrim()的組合將在這裏幫助。

$values = array(
    ''          => '/' 
    , '/////'         => '/' 
    , '///text//'        => '/text/' 
    , '/text/?var=text'       => '/text/' 
    , '/text/?var=text/'      => '/text/var-text/' 
    , '/[email protected]#$%^&*(()_+|/#anchor'   => '/text/' 
    , '/[email protected]#$%^&*(()_+|text/[email protected]#$%^&*(()_+|text/' => '/text/text/' 
); 

foreach($values as $raw => $expected) 
{ 
    /* Remove '#'s that don't appear to be document fragments and anything 
    * else that's not a letter or one of '?' or '='. 
    */ 
    $url = preg_replace(array('|(?<!/)#|', '|[^?=#a-z/]+|i'), '', $raw); 

    /* Pull out the path and query strings from the resulting value. */ 
    $path = parse_url($url, PHP_URL_PATH); 
    $query = parse_url($url, PHP_URL_QUERY); 

    /* Ensure the path ends with '/'. */ 
    $friendly = rtrim($path, '/') . '/'; 

    /* If the query string ends with '/', append it to the path. */ 
    if(substr($query, -1) == '/') 
    { 
    /* Replace '=' with '-'. */ 
    $friendly .= str_replace('=', '-', $query); 
    } 

    /* Clean up repeated slashes. */ 
    $friendly = preg_replace('|/{2,}|', '/', $friendly); 

    /* Check our work. */ 
    printf(
    'Raw: %-42s - Friendly: %-18s (Expected: %-18s) - %-4s' 
     , "'$raw'" 
     , "'$friendly'" 
     , "'$expected'" 
     , ($friendly == $expected) ? 'OK' : 'FAIL' 
); 
    echo PHP_EOL; 
} 

上面的代碼輸出:

 
Raw: ''           - Friendly: '/'    (Expected: '/'    ) - OK 
Raw: '/////'         - Friendly: '/'    (Expected: '/'    ) - OK 
Raw: '///text//'        - Friendly: '/text/'   (Expected: '/text/'   ) - OK 
Raw: '/text/?var=text'       - Friendly: '/text/'   (Expected: '/text/'   ) - OK 
Raw: '/text/?var=text/'       - Friendly: '/text/var-text/' (Expected: '/text/var-text/') - OK 
Raw: '/[email protected]#$%^&*(()_+|/#anchor'    - Friendly: '/text/'   (Expected: '/text/'   ) - OK 
Raw: '/[email protected]#$%^&*(()_+|text/[email protected]#$%^&*(()_+|text/' - Friendly: '/text/text/'  (Expected: '/text/text/' ) - OK 

注意,此代碼並根據您提供的例子通過,但它可能無法正常捕捉你所要完成什麼樣的意圖。我已經評論了代碼以解釋它的作用,以便您可以在必要時進行調整。

供您參考:

相關問題