tags:

views:

302

answers:

3

I got the following code from this question: http://stackoverflow.com/questions/539920/what-is-the-best-way-to-clean-a-string-for-placement-in-a-url-like-the-question

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

This code works for me with PHP, its making clean and SEO'd url's in just one line, but I want to use the same script in my ASP.NET(C#) application. But don't know what will be the code for this line in C#. Can anyone please convert this PHP code into C# function.

Thanks

A: 

This answer might help you:

http://stackoverflow.com/questions/166855/c-pregreplace

Kieran Hall
+1  A: 

To keep it simple, it's probably easiest to do it with two regex replace calls, though you could rewrite it into one using the Replace overload with MatchEvaluator (it would be a bit hacky).

using System.Text.RegularExpressions;

// ...

var str = Regex.Replace(Regex.Replace(urlPart, @"[^a-z0-9\- ]/i", ""), @"[ \-]+", "-").ToLower();

Hope that helps.

Noldorin
It's not replacing the special chars, in short its not making the URL SEO'd (dash delimited) :(
Prashant
@Prashant: Could you be a bit more specific about how it doesn't work? It's directly converted from the PHP, so unless there's a difference in regex functionality I don't see the problem. (I do however admit it's not tested.)
Noldorin
Prashant
@Prashant: Yeah, so I'm not too familiar with string literals in PHP. Try the fixed version (I've edited the post).
Noldorin
Prashant
A: 

I may be missing something due to lack of sleep.. but couldn't you just simply do this:

var myUrl = HttpUtility.UrlEncode(UrlToEncode);

To do dash encoding...

var myUrl = HttpUtility.EncodeUrl(UrlToEncode.Replace(" ", "-"));
datacop
Hey @daracop I think you're not getting my question due to sleep :) anyways, I want to convert a title "ASP.NET caching techniques" to "asp-net-caching-techniques" so that I can serve the better URL to search engines. Like SO is doing http://stackoverflow.com/questions/812083/how-to-convert-this-php-script-into-c
Prashant
HttpUtility.UrlEncode(UrlToEncode); will not convert my title to dash delimited URL.
Prashant
Ok.. so I made an edit to my answer.. It just seems to me like you're trying to use a cannon to kill a mosquito.
datacop
So waht about, special characters ??? they'll look like %23 or simillar in URL's or sometimes, I receieved title with double spaces, that was some mistak by user, but I can't teach my user to only type single space. If double space is the case then your code will make my title like "Microsoft and Google" to "Microsoft-and--Google" I don't think its will look cute. You're not getting the concept properly.
Prashant
Take StackOverflow as examaple, why they are making there URL nicer? caz they want to serve a good URL to search engines, which will increase there ranking among the different search engines....
Prashant