看起來像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
注意,此代碼並根據您提供的例子通過,但它可能無法正常捕捉你所要完成什麼樣的意圖。我已經評論了代碼以解釋它的作用,以便您可以在必要時進行調整。
供您參考:
我不明白 - 你想在.htaccess中? – deviousdodo 2011-12-14 15:03:51
自從你最後一個問題以來,你有沒有試圖學習正則表達式? [man](http://www.php.net/manual/en/reference.pcre.pattern.syntax.php)或[ri](http://regular-expressions.info/) - 只需發佈需求並詢問代碼是無關緊要的。 – mario 2011-12-14 15:06:19