php 去除php变量,用破折号替换空格

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11330480/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 00:17:32  来源:igfitidea点击:

Strip php variable, replace white spaces with dashes

php

提问by Rob

How can I convert a PHP variable from "My company & My Name" to "my-company-my-name"?

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

I need to make it all lowercase, remove all special characters and replace spaces with dashes.

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

回答by rorypicko

This function will create an SEO friendly string

此函数将创建一个 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;
}

should be fine :)

应该没事 :)

回答by NoLifeKing

Replacing specific characters: http://se.php.net/manual/en/function.str-replace.php

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

Example:

例子:

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

回答by Pierre Voisin

Yop, and if you want to handle any special characters you'll need to declare them in the pattern, otherwise they may get flushed out. You may do it that way:

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

strtolower(preg_replace('/-+/', '-', preg_replace('/[^\wáéíóú]/', '-', $string)));