Tom*_*Tom 12
每当我想将标题或其他字符串转换为URL slugs时,我都会使用以下代码.它通过使用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;
}
Run Code Online (Sandbox Code Playgroud)
如果您打算使用代码生成URL slugs,那么您可能需要考虑添加一些额外的代码,以便在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, '-'));
}
}
Run Code Online (Sandbox Code Playgroud)
bla*_*305 11
啊,我之前用过博客文章(用于网址).
码:
$string = preg_replace("/[^0-9a-zA-Z ]/m", "", $string);
$string = preg_replace("/ /", "-", $string);
Run Code Online (Sandbox Code Playgroud)
$string将包含过滤的文本.你可以回应它或用它做任何你想做的事情.