한 가지 방법은 통과 할 수
이제
string cleanString = originalString.ToLower().Replace(" ", "-"); // ToLower() on the string thenreplaces spaces with hyphens
cleanString = Regex.Replace(cleanString, @"[^a-zA-Z0-9\/_|+ -]", ""); // removes all non-alphanumerics/underscore/hyphens
당신의 문자열에 다음이다 cleanString
ActoinLink에 (제목, 이름 등을위한)/Url.Action 매개 변수를 사용하면 큰 효과를 볼 수 있습니다.
이 패턴은 몇 가지 정규식 영웅이 차임 및 좋은 것 더 나은 하나를 제공 할 수 있는지, 정규식 패턴에 100 %를 해요 http://snipplr.com/view/18414/string-to-clean-url-generator/
에서 가져온 것입니다. Regex 테스트에서 공백과 일치하지 않지만 첫 번째 줄은 모든 공백을 하이픈으로 바꾸기 때문에 문제가되지 않습니다.
업데이트 :
이 코드를 사용하려면, 당신은 추가 매개 변수를 허용하도록 설정에 경로를해야합니다.
블로그 기사 제목을 예로 사용합니다. 당신의 ASP.NET MVC 뷰에서
routes.MapRoute(
"", // Route name
"View/{ID}/{Title}", // URL with parameters
new { controller = "Articles", action = "View"} // Parameter defaults
);
, 당신은 다음을 수행 할 수 있습니다
<%= Html.ActionLink("View Article", "View", "Articles", new { ID = article.ID, Title = Html.SanitizeTitle(article.Title) }, null) %>
를 앞의 예에서, 나는 HTML helper로 SanitizeTitle
를 사용합니다.
public static SanitizeTitle(this HtmlHelper html, string str)
{
string cleanString = originalString.ToLower().Replace(" ", "-"); // ToLower() on the string thenreplaces spaces with hyphens
cleanString = Regex.Replace(cleanString, @"[^a-zA-Z0-9\/_|+ -]", ""); // removes all non-alphanumerics/underscore/hyphens
return cleanString;
}
대시 모든 비 단어 문자를 교체 그러나 나는 이것이 더 좋을 것이라고 생각한다 : input = Regex.Replace (input, @ "[| \\ /]", "-"); // "깨는"문자를 "-"로 바꾸십시오. 입력 = Regex.Replace (입력, @ "[^ a-zA-Z0-9 -_. ~]", "")); // 나머지 안전하지 않은 (RFC3986) 문자를 " input = input.Trim (new [] { '-', '_', '.', '~'})로 바꿉니다. // 영숫자가 아닌 문자를 앞뒤로 자르고 소문자로 변환 – JohannesH
쓰레기 ... 주석에 줄 바꿈이 없습니다. – JohannesH