duanpasi6287 2014-01-08 13:05 采纳率: 100%
浏览 30
已采纳

从名称生成适当的链接

I am attempting to generate proper links from proper names...

For example: T & J Automotive is currently generated as /t-j-automotive

But, because I need to do a look up based on the name, I am unable to do said lookup when attempting to convert back to the name.

So... I've take care of ' by converting them to _, which works great for names like Mike's Shop (converts to mike_s-shop), but now I am faced with the &

Here is my current function:

// 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;
}

Note, the & replacement is not happenning. How can I make sure that any string passed to this function will have ' replace with _, and & replaced with .?

  • 写回答

1条回答 默认 最新

  • dragon456101 2014-01-08 13:19
    关注

    Fixed:

    // 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;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题