5

可能重复:
PHP 中的 URL 友好用户名?

我有这样的事情:

'mrt1' => 'Zhongxiao Dunhua Sun'

它将包含在这样的锚链接中:

<a href="'. $mrt1 .'">'. $mrt1 .'</a>

我希望输出是这样的:

<a href="zhongxiao-dunhua-sun">Zhongxiao Dunhua Sun</a>

如何做到这一点,以便我可以将该名称转换为 URL 友好的字符串(以便我可以将其放在 href 属性中)?

4

4 回答 4

12
$s = ' Zhongxiao Dunhua Sun ';
$r = preg_replace('/\W+/', '-', strtolower(trim($s)));
echo("$r\n");
于 2012-12-13T05:18:18.857 回答
3

PHP 具有使字符串符合 URL 标准的功能:

urlencode($mrt1);
于 2012-12-13T05:22:17.020 回答
2

你也可以试试这个功能..

function create_seo_link($text) {
    $letters = array(
        '–', '—', '"', '"', '"', '\'', '\'', '\'',
        '«', '»', '&', '÷', '>',    '<', '$', '/'
    );

    $text = str_replace($letters, " ", $text);
    $text = str_replace("&", "and", $text);
    $text = str_replace("?", "", $text);
    $text = strtolower(str_replace(" ", "-", $text));

    return ($text);
}
于 2012-12-13T05:26:40.990 回答
1

str_replace()将空格更改为-strtolower()更改为小写。

$mrt1 = 'Zhongxiao Dunhua Sun';
$mrt1 = str_replace(' ','-',strtolower($mrt1));
于 2012-12-13T05:18:40.977 回答