【问题标题】:Strip php variable, replace white spaces with dashes剥离 php 变量,用破折号替换空格
【发布时间】:2012-07-05 00:57:36
【问题描述】:

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

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

【问题讨论】:

标签: php


【解决方案1】:

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

应该没问题:)

【讨论】:

  • 谢谢。这是一个不错的简单功能,可以扩展以去除某些对 seo 不友好的关键字,例如“the”和“and”。
  • This question 暗示不值得去掉“停止”词;我创建了一个gist,它为 rory 的解决方案添加了重音字符处理。
  • 如何删除没有-符号的第一个和最后一个空格?
  • @Kvvaradha 将以下行粘贴到函数$string = trim($string); 中的第一行,这将解决您的问题。
  • 这个怎么用
【解决方案2】:

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

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

【讨论】:

    【解决方案3】:

    替换特定字符: 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;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-25
      • 2013-12-11
      相关资源
      最近更新 更多