首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >有PHP函数从自然文本生成漂亮有效的URL吗?

有PHP函数从自然文本生成漂亮有效的URL吗?
EN

Stack Overflow用户
提问于 2009-11-25 12:39:45
回答 7查看 572关注 0票数 4

我想从任何自然文本自动生成一个可读的URL,如下所示:

最新文章:关于德国信件-处理!

在理想情况下会改为

latest-article-about-german-letters-handling-aou-and-ss.html

它应该适用于所有拉丁语,我想避免任何逃避。

我想这可以通过正则表达式来实现,但是在PHP/PEAR/PECL中可能已经有了一个标准函数。

EN

回答 7

Stack Overflow用户

回答已采纳

发布于 2009-11-25 12:44:25

你要找的是污垢你的短信。

您可以在Internet上找到代码片段,例如这段代码将起到以下作用:

代码语言:javascript
运行
复制
/**
 * Modifies a string to remove al non ASCII characters and spaces.
 */
static public function slugify($text)
{
    // replace non letter or digits by -
    $text = preg_replace('~[^\\pL\d]+~u', '-', $text);

    // trim
    $text = trim($text, '-');

    // transliterate
    if (function_exists('iconv'))
    {
        $text = iconv('utf-8', 'us-ascii//TRANSLIT', $text);
    }

    // lowercase
    $text = strtolower($text);

    // remove unwanted characters
    $text = preg_replace('~[^-\w]+~', '', $text);

    if (empty($text))
    {
        return 'n-a';
    }

    return $text;
}

来自这里

票数 11
EN

Stack Overflow用户

发布于 2009-11-25 12:44:54

我不认为有这样的功能,但我最近创建了这样的功能:

代码语言:javascript
运行
复制
function fix_url($word) {
    /**
     * whilst the descriptor in the url will be for SEO     
     * purposes only, we need to ensure it doesn't break
     * the URI rules http://www.faqs.org/rfcs/rfc2396.html
     */  

    // convert to lower case
    $word=strtolower($word);

    // define illegal / replacement characters
    $illegal = array("ä","ö","ü","ß");
    $replace = array("a","o","u","ss");
    $word = str_replace($illegal, $replace, $word);

    // remove & for and
    $word=str_replace("&","and",$word);

    // remove a space for -
    $word=str_replace(" ","-",$word);

    // and replace all non alphanumeric characters or a dash
    $word=ereg_replace("[^A-Za-z0-9-]", "", $word);
    return $word;
}

我列举了一个用安全字符代替非法人物的例子。

我已经测试了这段代码,它返回了latest-article-about-german-letters---handling-aou-and-ss,所以很明显还有一些调整要做(参见--),但是我确信这是很容易适应的。

票数 3
EN

Stack Overflow用户

发布于 2009-11-25 13:44:22

从一段时间以来,我成功地使用了来自PHP UTF8库的PHP UTF8。作品任何UTF-8文本(包括非拉丁文)。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/1796674

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档