我怎么能忽略单引号呢?
function FixNameForLink($str){
// Swap out Non "Letters" with a -
$text = preg_replace('/[^''pL'd]+/u', '-', $str);
// Trim out extra -'s
$text = trim($text, '-');
// Convert letters that we have left to the closest ASCII representation
$text = iconv('utf-8', 'us-ascii//TRANSLIT', $text);
// Make text lowercase
$text = strtolower($text);
// Strip out anything we haven't been able to convert
$text = preg_replace('/[^-_'w]+/', '', $text);
return $text;
}
我有一个名字Steven's Barbecue
,我想将其转换为正确的链接,例如steven-s-barbecue
,但不知何故,我需要能够将'转换为另一个字符,例如_
为了澄清(以避免混淆...),需要steven_s-barbecue
链接
解决方案是允许在初始替换中使用引号字符,然后在末尾用 _ 替换它。示例如下:
<?php
function FixNameForLink($str){
// Swap out Non "Letters" with a -
$text = preg_replace('/[^'pL'd'']+/u', '-', $str);
// Trim out extra -'s
$text = trim($text, '-');
// Convert letters that we have left to the closest ASCII representation
$text = iconv('utf-8', 'us-ascii//TRANSLIT', $text);
// Make text lowercase
$text = strtolower($text);
// ' has been valid until now... swap it for an _
$text = str_replace('''', '_', $text);
// Strip out anything we haven't been able to convert
$text = preg_replace('/[^-_'w]+/', '', $text);
return $text;
}
var_dump(FixNameForLink("Steven's Barbecue")); // steven_s-barbecue
运行str_replace
?
$text = str_replace("'", '_', $str);
$text = preg_replace('/[^_''pL'd]+/u', '-', $text);
为了安全起见,您还可以在所有函数之后运行urlencode()
到最终产品,因为您尝试使用破折号而不是空格%20