2013-12-18 67 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的空間

相關問題