我有这个 javascript 函数,可以将任何字符串转换为完美的 slug(在我看来)。
function slugGenerator(str) {
str = str.replace(/^\s+|\s+$/g, '');
str = str.toLowerCase();
var from = "àáäâèéëêìíïîòóöôùúüûñç·/_,:;";
var to = "aaaaeeeeiiiioooouuuunc------";
for (var i=0, l=from.length ; i<l ; i++) {
str = str.replace(new RegExp(from.charAt(i), 'g'), to.charAt(i));
}
str = str.replace(/[^a-z0-9 -]/g, '').replace(/\s+/g, '_').replace(/-+/g, '-');
return str;
}
我需要将其转换为 PHP,我已经尝试过,结果是:
function slugGenerator($str) {
$str = preg_replace('/^\s+|\s+$/g', '', $str);
$str = strtolower($str);
$from = "àáäâèéëêìíïîòóöôùúüûñç·/_,:;";
$to = "aaaaeeeeiiiioooouuuunc------";
for ($i = 0, $l = strlen($from); $i<$l ; $i++) {
$str = str.replace(new RegExp(from.charAt(i), 'g'), to.charAt(i));
}
$str = preg_replace('/[^a-z0-9 -]/g', '', $str)
$str = preg_replace('/\s+/g', '_', $str)
$str = preg_replace('/-+/g', '-', $str);
return $str;
}
我有这个for循环的问题:
for ($i = 0, $l = strlen($from); $i<$l ; $i++) {
// This string
$str = str.replace(new RegExp(from.charAt(i), 'g'), to.charAt(i));
}
我不知道如何将其转换为 PHP,有人可以尝试转换它吗?
解决方案: 添加strtr_unicode函数并使用此脚本:
function slugGenerator($str) {
$str = preg_replace('/^\s+|\s+$/', '', $str);
$str = strtolower($str);
$from = "àáäâèéëêìíïîòóöôùúüûñç·/_,:;";
$to = "aaaaeeeeiiiioooouuuunc------";
$str = strtr_unicode($str, $from, $to);
$str = preg_replace(
array("~[^a-z0-9 -]~i", "~\s+~", "~-+~"),
array("", "_", "-"),
$str
);
return $str;
}