Php 如何将字符串转换为字母数字,并将空格转换为破折号?
我想取一个字符串,去掉所有非字母数字字符,并将所有空格转换成破折号 啊,我以前在博客帖子(url)中使用过这个 代码:Php 如何将字符串转换为字母数字,并将空格转换为破折号?,php,Php,我想取一个字符串,去掉所有非字母数字字符,并将所有空格转换成破折号 啊,我以前在博客帖子(url)中使用过这个 代码: $string将包含筛选的文本。您可以回显它,也可以使用它执行任何操作。每当我想将标题或其他字符串转换为URL段塞时,我都会使用以下代码。通过使用正则表达式将任何字符串转换为字母数字字符和连字符,它可以满足您的所有要求 function generateSlugFrom($string) { // Put any language specific filters he
$string
将包含筛选的文本。您可以回显它,也可以使用它执行任何操作。每当我想将标题或其他字符串转换为URL段塞时,我都会使用以下代码。通过使用正则表达式将任何字符串转换为字母数字字符和连字符,它可以满足您的所有要求
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, '-'));
}
}
如果你喜欢这个答案,请点击这篇文章右边的复选标记。第二行不是应该先做吗?另外,在你的第一个preg_replace语句末尾的“m”的确切目的是什么?感谢Decoy提到的第二行不会替换任何内容,因为任何非字母数字字符都将被第一行替换,其中包括空格。@Josh我17分钟前就解决了这个问题。@blake305我道歉。我一定很快就忽略了这个空间。通常,我会在regex中查找速记空白字符类
\s
,以避免任何混淆。此类的可能重复非常好,感谢您共享代码。这正是我想要的。
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(array('/[^[:alnum:]]/', '/(\s+|\-{2,})/'), array('', '-'), $string);