2013-12-18 65 views
-1

如何忽略通过此操作实现的单引号?如何忽略正则表达式中的单个字符

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

+0

为什么不只是使用urlencode()? – 2013-12-18 18:55:48

+0

,因为我不需要在网址中使用空格之类的+或%20 ...我需要 - 。 – Kevin

+0

那么'\\ pL'包含撇号? –

回答

3

的解决方案将是允许在初始替换中使用引号字符,然后在最后用_替换。示例如下:

<?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 
+0

谢谢。我认为我的困惑是因为我认为'$ text = preg_replace('/ [^ \\ pL \ d \'] +/u',' - ',$ str);'是先剥离掉所有东西。 – Kevin

+1

[^ XXXX]组表示匹配除这些字符以外的任何内容,而+表示一个或多个。所以这就是说替换一切,但是“字母字符”(\ pL),数字(\ d)和单引号(\')。在p之前的\ \实际上是多余的,可以缩写为\ p。我已经编辑了上面的内容来反映这一点。 –

1

运行一个str_replace

$text = str_replace("'", '_', $str); 
$text = preg_replace('/[^_\\pL\d]+/u', '-', $text); 

您也可以运行后您的所有功能于最终产品urlencode()只是为了安全起见,因为你试图使用破折号,而不是%20的空间

相关问题