2011-12-14 58 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 

注意,此代码并根据您提供的例子通过,但它可能无法正常捕捉你所要完成什么样的意图。我已经评论了代码以解释它的作用,以便您可以在必要时进行调整。

供您参考:

相关问题