【问题标题】:Help to port php function for do "clean url" to c#帮助将 php 函数移植到 c#
【发布时间】:2011-07-12 15:38:57
【问题描述】:

我正在尝试将此函数移植到 c#

http://www.phpsnaps.com/snaps/view/clean-url/

我在正则表达式 charp 命名法中转换 ""~[^-a-z0-9_]+~"(php 模式命名法)时遇到问题。

<?php

function cleanURL($string)
{
    $url = str_replace("'", '', $string);
    $url = str_replace('%20', ' ', $url);
    // (PROBLEM) substitutes anything but letters, numbers and '_' with separator
    $url = preg_replace('~[^\pL0-9_]+~u', '-', $url);
    $url = trim($url, "-");
    // you may opt for your own custom character map for encoding.
    $url = iconv("utf-8", "us-ascii//TRANSLIT", $url); 
    $url = strtolower($url);
     (PROBLEM)
    $url = preg_replace('~[^-a-z0-9_]+~', '', $url); // keep only letters, numbers, '_' and separator
    return $url;
} // echo cleanURL("Shelly's%20Greatest%20Poem%20(2008)");  // shellys-greatest-poem-2008
?>

这是c#函数:

static String cleanURL(String url)
{
    url = url.Replace("'", "");
    url = url.Replace("%20", " ");            
    url = System.Text.RegularExpressions.Regex.Replace(url, "~[^\pL0-9_]+~u", "-");           
    url = url.Trim(new char[1]{'-'});         

    Encoding ascii = Encoding.ASCII;           
    Encoding utf8 = Encoding.UTF8;           
    byte[] utf8bytes = utf8.GetBytes(url);           
    byte[] asciiBytes = Encoding.Convert(utf8, ascii, utf8bytes);            
    char[] asciiChars = new char[ascii.GetCharCount(asciiBytes, 0, asciiBytes.Length)];           
    ascii.GetChars(asciiBytes, 0, asciiBytes.Length, asciiChars, 0);           

    url = new string(asciiChars);           
    url = url.ToLower();                    
    url = System.Text.RegularExpressions.Regex.Replace(url, "~[^-a-z0-9_]+~", "");
    return url;           
}    

谢谢。有谁能帮帮我?

【问题讨论】:

  • 您需要发布您遇到的确切问题,而不是要求我们转换整段代码。
  • 问题出在描述中,它的 php vs c# 正则表达式!
  • @Bob:这里没有问题
  • “我在正则表达式 charp 命名法中转换 ""~[^-a-z0-9_]+~" (php 模式命名法)时遇到问题。” - 这就是问题的描述结束请求帮助?

标签: c# php regex clean-url


【解决方案1】:

开始和结束处的~只是模式开始结束标记,c#格式不需要它们

所以~[^-a-z0-9_]~ 应该只是[^-a-z0-9_]

第一个模式末尾的 u 使 php 将该模式视为 UTF8,你不应该需要这个。

【讨论】:

    猜你喜欢
    • 2011-12-17
    • 2010-09-10
    • 1970-01-01
    • 2010-11-10
    • 1970-01-01
    • 2010-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多