首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >去掉php变量,用短划线替换空格

去掉php变量,用短划线替换空格
EN

Stack Overflow用户
提问于 2012-07-04 21:54:01
回答 3查看 95.6K关注 0票数 75

如何将PHP变量从"My company & My Name“转换为"my-company-my-name"?

我需要让它全部小写,删除所有特殊字符,并用破折号替换空格。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2012-07-04 21:56:27

此函数将创建SEO友好的字符串

function seoUrl($string) {
    //Lower case everything
    $string = strtolower($string);
    //Make alphanumeric (removes all other characters)
    $string = preg_replace("/[^a-z0-9_\s-]/", "", $string);
    //Clean up multiple dashes or whitespaces
    $string = preg_replace("/[\s-]+/", " ", $string);
    //Convert whitespaces and underscore to dash
    $string = preg_replace("/[\s_]/", "-", $string);
    return $string;
}

应该没问题:)

票数 255
EN

Stack Overflow用户

发布于 2012-07-04 22:06:35

替换特定字符:http://se.php.net/manual/en/function.str-replace.php

示例:

function replaceAll($text) { 
    $text = strtolower(htmlentities($text)); 
    $text = str_replace(get_html_translation_table(), "-", $text);
    $text = str_replace(" ", "-", $text);
    $text = preg_replace("/[-]+/i", "-", $text);
    return $text;
}
票数 9
EN

Stack Overflow用户

发布于 2012-07-04 22:33:50

是的,如果你想处理任何特殊的字符,你需要在模式中声明它们,否则它们可能会被清除。你可以这样做:

strtolower(preg_replace('/-+/', '-', preg_replace('/[^\wáéíóú]/', '-', $string)));
票数 8
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11330480

复制
相关文章

相似问题

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