【问题标题】:How to convert a string to alphanumeric and convert spaces to dashes? [closed]如何将字符串转换为字母数字并将空格转换为破折号? [关闭]
【发布时间】:2012-02-05 05:02:37
【问题描述】:

我想要一个字符串,去掉所有非字母数字字符并将所有空格转换为破折号。

【问题讨论】:

标签: php


【解决方案1】:

每当我想将标题或其他字符串转换为 URL slug 时,我都会使用以下代码。它通过使用 RegEx 将 any 字符串转换为字母数字字符和连字符来完成您所要求的一切。

function generateSlugFrom($string)
{
    // Put any language specific filters here, 
    // like, for example, turning the Swedish letter "å" into "a"

    // Remove any character that is not alphanumeric, white-space, or a hyphen 
    $string = preg_replace('/[^a-z0-9\s\-]/i', '', $string);
    // Replace all spaces with hyphens
    $string = preg_replace('/\s/', '-', $string);
    // Replace multiple hyphens with a single hyphen
    $string = preg_replace('/\-\-+/', '-', $string);
    // Remove leading and trailing hyphens, and then lowercase the URL
    $string = strtolower(trim($string, '-'));

    return $string;
}

如果您打算使用代码来生成 URL slug,那么您可能需要考虑添加一些额外的代码以在 80 个字符左右后将其剪切。

if (strlen($string) > 80) {
    $string = substr($string, 0, 80);

    /**
     * If there is a hyphen reasonably close to the end of the slug,
     * cut the string right before the hyphen.
     */
    if (strpos(substr($string, -20), '-') !== false) {
        $string = substr($string, 0, strrpos($string, '-'));
    }
}

【讨论】:

  • 这很好,感谢您分享您的代码。几乎正是我想要的。
【解决方案2】:

啊,我以前在博客文章中使用过这个(用于网址)。

代码:

$string = preg_replace("/[^0-9a-zA-Z ]/m", "", $string);
$string = preg_replace("/ /", "-", $string);

$string 将包含过滤后的文本。你可以回应它或用它做任何你想做的事情。

【讨论】:

  • 如果你喜欢这个答案,请点击这篇文章右边的勾号。
  • 不应该先完成第二行吗?另外,第一个 preg_replace 语句末尾的“m”到底是什么目的?谢谢
  • 就像 Decoy 提到的那样,第二行不会替换任何内容,因为任何非字母数字字符都将被第一行替换,其中包括空格。
  • @Josh 我在 17 分钟前修复了这个问题...
  • @blake305 抱歉。我一定很快忽略了这个空间。通常,我会在正则表达式中查找速记空白字符类 \s 以避免任何混淆。
【解决方案3】:
$string = preg_replace(array('/[^[:alnum:]]/', '/(\s+|\-{2,})/'), array('', '-'), $string);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-01
    • 2020-01-12
    • 2021-03-28
    • 2017-12-28
    • 1970-01-01
    • 1970-01-01
    • 2018-05-02
    相关资源
    最近更新 更多