What is the best way to clean a string for placement in a URL, like the question name on SO?

后端 未结 1 830
清酒与你
清酒与你 2021-01-01 02:08

I\'m looking to create a URL string like the one SO uses for the links to the questions. I am not looking at rewriting the url (mod_rewrite). I am looking at generating the

1条回答
  •  迷失自我
    2021-01-01 02:56

    As you pointed out already, urlencode() is not needed in this case and neither is trim(). If I understand correctly, step 4 is to avoid multiple dashes in a row, but it will not prevent more than two dashes. On the other hand, dashes connecting two words (like in "large-scale") will be removed by your solution while they seem to be preserved on SO.

    I'm not sure that this is really the best way to do it, but here's my suggestion:

    $str = strtolower( 
      preg_replace( array('/[^a-z0-9\- ]/i', '/[ \-]+/'), array('', '-'), 
      $urlPart ) );
    

    So:

    1. remove any character that is neither space, dash, nor alphanumeric
    2. replace any consecutive number of spaces or dashes with a single dash
    3. strtolower()

    0 讨论(0)
提交回复
热议问题