2014-01-08 93 views
0

我试图生成正确的名称正确的链接正确的链接...生成从名称

例如:牛逼&Ĵ汽车目前为/TJ-汽车

但产生的,因为我需要根据名称进行查找,所以在尝试转换回名称时,我无法进行查找。

所以......我已经将他们照顾“到_,这对于像迈克的店名的伟大工程(转换为mike_s店),但现在我面临的&

这里是我目前的功能:

// Fix the name for a SEO friendly URL 
function FixNameForLink($str){ 
    // Swap out Non "Letters" with a - 
    $text = preg_replace('/[^\\pL\d\']+/u', '-', $str); 
    // Trim out extra -'s 
    $text = trim($text, '-'); 
    // Convert letters that we have left to the closest ASCII representation 
    $text = iconv('utf-8', 'us-ascii//TRANSLIT', $text); 
    // Make text lowercase 
    $text = strtolower($text); 
    // ' has been valid until now... swap it for an _ 
    $text = str_replace('\'', '_', $text); 
    // & has been valid until now... swap it for an . 
    $text = str_replace('&', '.', $text); 
    // Strip out anything we haven't been able to convert 
    $text = preg_replace('/[^-_\w]+/', '', $text); 
    return $text; 
} 

请注意,&替代不会发生。我怎样才能确保传递给这个函数的任何字符串都会用_替代,并用012替代。

+1

你的代码中包含的操作,一般是不可逆的,因此无法得到原始输入从固定名称开始。你在这方面走错了路。如果你需要原始输入然后保存它。 – Jon

+0

请重新阅读我需要的内容...这是在问题中。我了解你的顾虑,但我的需求与他们不同。 – Kevin

+0

您写下“我试图转换回名称时无法进行查找”。我的意思是说你不能*在一般情况下转换回名字,因为你正在做一些事情,比如不加区分地用短划线替换字符。当你的需求与现实相冲突时,现实总会获胜。 – Jon

回答

0

修正:

// Fix the name for a SEO friendly URL 
function FixNameForLink($str){ 
    // Swap out Non "Letters" with a - 
    $text = preg_replace('/[^\\pL\d\'&]+/u', '-', $str); // needed to allow the & 
    // Trim out extra -'s 
    $text = trim($text, '-'); 
    // Convert letters that we have left to the closest ASCII representation 
    $text = iconv('utf-8', 'us-ascii//TRANSLIT', $text); 
    // Make text lowercase 
    $text = strtolower($text); 
    // ' has been valid until now... swap it for an _ 
    $text = str_replace('\'', '_', $text); 
    // & has been valid until now... swap it for an . 
    $text = str_replace('&', '.', $text); 
    // Strip out anything we haven't been able to convert 
    $text = preg_replace('/[^-_\.\w]+/', '', $text); // needed to make sure the replace . stays put 
    return $text; 
}