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

正则表达式清理(PHP)

  •  17
  • Atif  · 技术社区  · 16 年前

    我想清理一个URL中的字符串,所以这是我基本上需要的。

    1. 必须删除除字母数字字符、空格和虚线之外的所有内容。
    2. 空格应该转换成破折号。

    如。

    This, is the URL!
    

    必须返回

    this-is-the-url
    
    5 回复  |  直到 16 年前
        1
  •  42
  •   SilentGhost    16 年前
    function slug($z){
        $z = strtolower($z);
        $z = preg_replace('/[^a-z0-9 -]+/', '', $z);
        $z = str_replace(' ', '-', $z);
        return trim($z, '-');
    }
    
        2
  •  3
  •   Victor Bocharsky    12 年前

    第一个去掉不需要的字符

    $new_string = preg_replace("/[^a-zA-Z0-9\s]/", "", $string);
    

    然后更改解封空间

    $url = preg_replace('/\s/', '-', $new_string);
    

    最后对其进行编码以备使用

    $new_url = urlencode($url);
    
        3
  •  1
  •   Community Mohan Dere    9 年前

    试试这个

     function clean($string) {
           $string = str_replace(' ', '-', $string); // Replaces all spaces with hyphens.
           $string = preg_replace('/[^A-Za-z0-9\-]/', '', $string); // Removes special chars.
    
           return preg_replace('/-+/', '-', $string); // Replaces multiple hyphens with single one.
        }
    

    用途:

    echo clean('a|"bc!@£de^&$f g');
    

    意志产出: abcdef-g

    来源: https://stackoverflow.com/a/14114419/2439715

        4
  •  0
  •   user1484291    10 年前

    这将在Unix shell中实现(我刚在MacOS上尝试过):

    $ tr -cs A-Za-z '-' < infile.txt > outfile.txt
    

    我是从一篇博客上得到这个想法的 More Shell, Less Egg

        5
  •  0
  •   Denis Matafonov    9 年前

    所有以前的asnwers都处理url,但如果有人需要清理登录字符串(例如)并将其保留为文本,请执行以下操作:

    function sanitizeText($str) {
        $withSpecCharacters = htmlspecialchars($str);
        $splitted_str = str_split($str);
        $result = '';
        foreach ($splitted_str as $letter){
            if (strpos($withSpecCharacters, $letter) !== false) {
                $result .= $letter;
            }
        }
        return $result;
    }
    
    echo sanitizeText('ОРРииыфвсси ajvnsakjvnHB "&nvsp;\n" <script>alert()</script>');
    //ОРРииыфвсси ajvnsakjvnHB &nvsp;\n scriptalert()/script
    //No injections possible, all info at max keeped