2012-01-08 68 views
4

我想取一个字符串,将其除去所有非字母数字字符并将所有空格转换为破折号。如何将字符串转换为字母数字并将空格转换为破折号?

+1

[PHP /正则表达式: “linkify” 博客标题]的可能重复(http://stackoverflow.com/questions/3244651/php-regex-linkify-blog-titles)的 – mario 2012-01-08 03:57:51

+0

可能的复制[php/regex:“linkify”博客标题](https://stackoverflow.com/questions/3244651/php-regex-linkify-blog-titles) – primpap 2017-09-13 22:05:54

回答

10

无论何时我想将标题或其他字符串转换为URL段落,我都会使用以下代码。它通过使用RegEx将任何字符串转换为字母数字字符和连字符来完成您要求的所有功能。

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蛞蝓的代码,那么你可能需要考虑增加一些额外的代码后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, '-')); 
    } 
} 
+0

这非常好,谢谢分享你的代码。几乎正是我所期待的。 – Decoy 2012-01-08 09:07:40

11

啊,我以前用过这篇博文(对于url)。

代码:

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

$string将包含过滤文本。你可以回应它或做任何你想要的东西。

+0

如果你喜欢这个答案,请点击右边的复选标记帖子。 – blake305 2012-01-08 03:57:49

+0

不应该先完成第二条线吗?另外,你的第一个preg_replace语句结尾的那个“m”的目的究竟是什么?谢谢 – Decoy 2012-01-08 04:14:54

+0

就像Decoy提到的那样,第二行不会代替任何东西,因为任何非字母数字字符已经被包含空格的第一行代替。 – Josh 2012-01-08 04:38:31

0
$string = preg_replace(array('/[^[:alnum:]]/', '/(\s+|\-{2,})/'), array('', '-'), $string);