Php 从名称生成适当的链接
我正在尝试从专有名称生成适当的链接 例如:T&J Automotive当前生成为/T-J-Automotive 但是,因为我需要根据名称进行查找,所以在尝试转换回名称时无法进行上述查找 所以。。。我已经通过将它们转换为,这对于像Mike's Shop(转换为Mikes-Shop)这样的名字非常有效,但现在我面临着& 以下是我目前的职能:Php 从名称生成适当的链接,php,regex,Php,Regex,我正在尝试从专有名称生成适当的链接 例如:T&J Automotive当前生成为/T-J-Automotive 但是,因为我需要根据名称进行查找,所以在尝试转换回名称时无法进行上述查找 所以。。。我已经通过将它们转换为,这对于像Mike's Shop(转换为Mikes-Shop)这样的名字非常有效,但现在我面临着& 以下是我目前的职能: // Fix the name for a SEO friendly URL function FixNameForLink($str){ // 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;
}
请注意,未发生更换(&p)。如何确保传递给此函数的任何字符串将具有“替换为”和“替换为”?修复:
// 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;
}
您的代码包含通常不可逆的操作,因此不可能从固定名称开始获取原始输入。你在这方面走错了路。如果您需要原始输入,请保存它。请重新阅读我需要的。。。这是个问题。我理解你的担忧,但我的需求与之不同。你写道“我无法在试图转换回名称时进行上述查找”。我的意思是,在一般情况下,你不能转换回名称,因为你在做一些事情,比如不加选择地用破折号替换字符。当你的需求与现实发生冲突时,现实总是赢的。