需要正则表达式来创建友好的url


Need a regular expression to create friendly URLs

很久以前我问过几乎相同的问题,但现在我需要更多更困难的东西。我需要相同的正则表达式代码工作为所有的请求(如果可能的话)

假设我有以下内容:

$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 = '/?text!@#$%^&*(()_+|/#anchor'; to output /text/
$friendly = '/!@#$%^&*(()_+|text/!@#$%^&*(()_+|text/'; to output /text/text/

希望这有意义!

似乎preg_replace(), parse_url()rtrim()的组合在这里会有所帮助。

$values = array(
    ''                                        => '/'
  , '/////'                                   => '/'
  , '///text//'                               => '/text/'
  , '/text/?var=text'                         => '/text/'
  , '/text/?var=text/'                        => '/text/var-text/'
  , '/?text!@#$%^&*(()_+|/#anchor'            => '/text/'
  , '/!@#$%^&*(()_+|text/!@#$%^&*(()_+|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;
}

以上代码输出:

<>之前原始:"-友好:'/'(预期:'/')-好的原始:'/////' -友好:'/'(预期:'/')-好的原始:'///text//' -友好:'/text/'(预期:'/text/') -好的生:"文本/?var=text' -友好:'/text/'(预期:'/text/') -好的生:"文本/?var=text/' -友好:'/text/var-text/'(预期:'/text/var-text/') -好的生:"文本/? !@#$%^&*(()_+|/# 锚 ' - 友好:"/文本/' ( 预期:"/文本/' ) - 好吧生 : '/!@#$%^&*(()_+| 文本/!@#$%^&*(()_+| 文本/"——友好:"/文本/文本"(预计:"文本/文本/' ) - 好吧之前

请注意,这段代码确实可以通过您提供的示例,但它可能无法正确捕获您试图完成的目的。我已经注释了代码来解释它的作用,以便您可以在必要的地方进行调整。

供参考:

  • parse_url()
  • preg_replace()
  • printf()
  • rtrim()
  • str_replace()
  • substr()