2010-03-15 70 views
1

我有我的課如何從URL中刪除所有特殊字符?

public function convert($title) 
    { 
     $nameout = strtolower($title); 
     $nameout = str_replace(' ', '-', $nameout); 
     $nameout = str_replace('.', '', $nameout); 
     $nameout = str_replace('æ', 'ae', $nameout); 
     $nameout = str_replace('ø', 'oe', $nameout); 
     $nameout = str_replace('å', 'aa', $nameout); 
     $nameout = str_replace('(', '', $nameout); 
     $nameout = str_replace(')', '', $nameout); 
     $nameout = preg_replace("[^a-z0-9-]", "", $nameout);  

     return $nameout; 
    } 

,但我不能讓我在使用特殊字符,如öü等它的工作,sombody能幫助我在這裏?我使用PHP 5.3。

+1

爲什麼你需要準確刪除變音符號?如果只是讓它通過一個HTTP URL,你可以使用'urlencode'。 – zneak 2010-03-15 17:04:33

回答

2

又是怎麼回事:

<?php 
$query_string = 'foo=' . urlencode($foo) . '&bar=' . urlencode($bar); 
echo '<a href="mycgi?' . htmlentities($query_string) . '">'; 
?> 

來源:http://php.net/manual/en/function.urlencode.php

+0

沒有對不起,因爲它不像「å」到「aa」nad,如果我不轉換它,我會去「_」:) – ParisNakitaKejser 2010-03-15 17:14:57

1

我前一段時間寫了這個功能的一個項目我工作,無法獲得正則表達式來工作。它不是最好的方式,但它的工作原理。

function safeURL($input){ 
    $input = strtolower($input); 
    for($i = 0; $i < strlen($input); $i++){ 
     $working = ord(substr($input,$i,1)); 
     if(($working>=97)&&($working<=122)){ 
      //a-z 
      $out = $out . chr($working); 
     } elseif(($working>=48)&&($working<=57)){ 
      //0-9 
      $out = $out . chr($working); 
     } elseif($working==46){ 
      //. 
      $out = $out . chr($working); 
     } elseif($working==45){ 
      //- 
      $out = $out . chr($working); 
     } 
    } 
    return $out; 
} 
0

下面就來幫助你在做什麼的功能,它是寫在 捷克:http://php.vrana.cz/vytvoreni-pratelskeho-url.phpand translated to English

這裏還有一個需要它(from the Symfony documentation):

<?php 
function slugify($text) 
{ 
    // replace non letter or digits by - 
    $text = preg_replace('~[^\\pL\d]+~u', '-', $text); 

    // trim 
    $text = trim($text, '-'); 

    // transliterate 
    if (function_exists('iconv')) 
    { 
    $text = iconv('utf-8', 'us-ascii//TRANSLIT', $text); 
    } 

    // lowercase 
    $text = strtolower($text); 

    // remove unwanted characters 
    $text = preg_replace('~[^-\w]+~', '', $text); 

    if (empty($text)) 
    { 
    return 'n-a'; 
    } 

    return $text; 
} 
相關問題