代码之家  ›  专栏  ›  技术社区  ›  ParisNakitaKejser

如何从URL中删除所有特殊字符?

  •  1
  • ParisNakitaKejser  · 技术社区  · 14 年前

    我有我的课

    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;
        }
    

    ö ü 另外,你能帮我吗?我使用PHP5.3。

    4 回复  |  直到 14 年前
        1
  •  3
  •   Community Tales Farias    7 年前

    第一个答案 this SO thread 包含执行此操作所需的代码。

        2
  •  2
  •   pvledoux    14 年前

    那么:

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

    发件人: http://php.net/manual/en/function.urlencode.php

        3
  •  1
  •   Jamescun    14 年前

    不久前,我为一个正在进行的项目编写了这个函数,但无法让RegEx工作。这不是最好的方法,但很管用。

    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;
    }
    
        4
  •  0
  •   camomileCase    14 年前

    这里有一个函数来帮助你做什么,它是用 捷克的: http://php.vrana.cz/vytvoreni-pratelskeho-url.php ( and 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;
    }