如何忽略RegEx中的单个字符

时间:2013-12-18 18:53:56

标签: php regex replace preg-replace str-replace

我怎样才能忽略单引号?

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,但不知怎的,我需要能够将'转换为另一个字符,如{{} 1}}

为了澄清(以避免混淆......),链接必须是_

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

运行str_replace

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

您也可以在完成所有功能之后运行urlencode()以确保安全,因为您尝试使用短划线代替%20空格