2010-03-15 71 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; 
} 
相关问题