且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

清除字符串以放置在URL中的***方法是什么,例如SO上的问题名称?

更新时间:2023-11-27 08:10:28

您已经指出,在这种情况下不需要urlencode(),而且trim()也不需要.如果我理解正确,则第4步是避免连续出现多个破折号,但它不会阻止两个以上的破折号.另一方面,连接两个单词的短划线(例如大范围")将被您的解决方案删除,而它们似乎保留在SO上.

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 ) );

所以:

  1. 删除任何既不是空格,破折号也不是字母数字的字符
  2. 用单个破折号替换任何连续数量的空格或破折号
  3. strtolower()