【发布时间】:2012-02-05 05:02:37
【问题描述】:
我想要一个字符串,去掉所有非字母数字字符并将所有空格转换为破折号。
【问题讨论】:
标签: php
我想要一个字符串,去掉所有非字母数字字符并将所有空格转换为破折号。
【问题讨论】:
标签: php
每当我想将标题或其他字符串转换为 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, '-'));
}
}
【讨论】:
啊,我以前在博客文章中使用过这个(用于网址)。
代码:
$string = preg_replace("/[^0-9a-zA-Z ]/m", "", $string);
$string = preg_replace("/ /", "-", $string);
$string 将包含过滤后的文本。你可以回应它或用它做任何你想做的事情。
【讨论】:
\s 以避免任何混淆。
$string = preg_replace(array('/[^[:alnum:]]/', '/(\s+|\-{2,})/'), array('', '-'), $string);
【讨论】: