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

时间:2022-08-29 16:49:14

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.

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

3 个解决方案

#1


204  

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 :)

应该很好:)

#2


8  

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

#3


6  

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:

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

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

#1


204  

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 :)

应该很好:)

#2


8  

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

#3


6  

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:

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

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