我想将友好的URL名称转换为:
Tom's Fish&Chips
Slug:tom-fish-and-Chips
1-2-3披萨
slu :: 1-2-3-Pizza
这里有一个功能:
<?php
function urlTitle($title) {
$title = preg_replace("/(.*?)([A-Za-z0-9\s]*)(.*?)/", "$2", $title);
$title = str_replace(' ', '-', $title);
$title = strtolower($title);
return $title;
}
echo urlTitle("Tom's Fish & Chips");
echo "<br />";
echo urlTitle("1-2-3 Pizza");
?>
Run Code Online (Sandbox Code Playgroud)
上面这个函数的行为几乎就是我想要的,因为我得到:
toms-fish--chips
123-pizza
Run Code Online (Sandbox Code Playgroud)
我该如何解决?
Dej*_*vic 10
function seo($input){
$input = str_replace(array("'", "-"), "", $input); //remove single quote and dash
$input = mb_convert_case($input, MB_CASE_LOWER, "UTF-8"); //convert to lowercase
$input = preg_replace("#[^a-zA-Z0-9]+#", "-", $input); //replace everything non an with dashes
$input = preg_replace("#(-){2,}#", "$1", $input); //replace multiple dashes with one
$input = trim($input, "-"); //trim dashes from beginning and end of string if any
return $input; //voila
}
Run Code Online (Sandbox Code Playgroud)
第二个preg_replace用一个替换多个破折号.
例子:
echo seo("Tom's Fish & Chips"); //toms-fish-chips
echo seo("1-2-3 Pizza"); //123-pizza
Run Code Online (Sandbox Code Playgroud)