正则表达式清理(PHP)

时间:2010-06-11 11:03:57

标签: php regex preg-replace sanitization

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

  1. 除字母数字字符和空格以及虚线外,必须删除所有内容。
  2. 空格应该转换成破折号。
  3. 例如

    This, is the URL!
    

    必须返回

    this-is-the-url
    

10 个答案:

答案 0 :(得分:42)

function slug($z){
    $z = strtolower($z);
    $z = preg_replace('/[^a-z0-9 -]+/', '', $z);
    $z = str_replace(' ', '-', $z);
    return trim($z, '-');
}

答案 1 :(得分:4)

首先删除不需要的字符

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

然后更改下划线的空格

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

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

$new_url = urlencode($url);

答案 2 :(得分:1)

试试这个

last page button

用法:

 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');

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

答案 3 :(得分:0)

这将在Unix shell中完成(我只是在我的MacOS上尝试过):

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

我从More Shell, Less Egg

上的博客文章中得到了这个想法

答案 4 :(得分:0)

之前的所有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

答案 5 :(得分:0)

您应该使用软包装,而不要重新发明轮子;)

https://github.com/cocur/slugify

答案 6 :(得分:0)

    function isolate($data) {
        
        $data = trim($data);
        $data = stripslashes($data);
        $data = htmlspecialchars($data);
        
        return $data;
    }

答案 7 :(得分:0)

OP并未明确描述describing的所有属性,但这是我从意图中收集的。

我对一个完美,有效,简洁的子弹的解释与这篇文章一致:https://wordpress.stackexchange.com/questions/149191/slug-formatting-acceptable-characters#:~:text=However%2C%20we%20can%20summarise%20the,or%20end%20with%20a%20hyphen

我发现没有一个较早发布的答案能够始终如一地实现这一目标(而且我什至没有扩展问题的范围以包括多字节字符)。

  1. 将所有字符转换为小写
  2. 将一个或多个字母数字字符的所有序列替换为单连字符。
  3. 从字符串中删除前和后的连字符。完成。

我建议使用以下单行代码,而不必费心声明一次性变量:

return trim(preg_replace('/[^a-z0-9]+/', '-', strtolower($string)), '-');

我还准备了一个演示,突出了其他答案中我认为不正确的地方。 (Demo

'This, is - - the URL!' input
'this-is-the-url'       expected

'this-is-----the-url'   SilentGhost
'this-is-the-url'       mario
'This-is---the-URL'     Rooneyl
'This-is-the-URL'       AbhishekGoel
'This, is - - the URL!' HelloHack
'This, is - - the URL!' DenisMatafonov
'This,-is-----the-URL!' AdeelRazaAzeemi
'this-is-the-url'       mickmackusa

---
'Mork & Mindy'      input
'mork-mindy'        expected

'mork--mindy'       SilentGhost
'mork-mindy'        mario
'Mork--Mindy'       Rooneyl
'Mork-Mindy'        AbhishekGoel
'Mork &amp; Mindy'  HelloHack
'Mork & Mindy'      DenisMatafonov
'Mork-&-Mindy'      AdeelRazaAzeemi
'mork-mindy'        mickmackusa

---
'What the_underscore ?!?'   input
'what-the-underscore'       expected

'what-theunderscore'        SilentGhost
'what-the_underscore'       mario
'What-theunderscore-'       Rooneyl
'What-theunderscore-'       AbhishekGoel
'What the_underscore ?!?'   HelloHack
'What the_underscore ?!?'   DenisMatafonov
'What-the_underscore-?!?'   AdeelRazaAzeemi
'what-the-underscore'       mickmackusa

答案 8 :(得分:0)

使用 intl transliterator 是一个不错的选择,因为有了它,您可以使用一组规则轻松处理复杂的情况。我添加了自定义规则来说明它如何灵活以及如何保留最多有意义的信息。随意删除它们并添加您自己的规则。

$strings = [
    'This, is - - the URL!',
    'Holmes & Yoyo',
    'L’Œil de démon',
    'How to win 1000€?',
    '€, $ & other currency symbols',
    'Und die Katze fraß alle mäuse.',
    'Белите рози на София',
    'പോണ്ടിച്ചേരി സൂര്യനു കീഴിൽ',
];

$rules = <<<'RULES'
# Transliteration
:: Any-Latin ;   :: Latin-Ascii ;

# examples of custom replacements
'&' > ' and ' ;
[^0-9][01]? { € > ' euro' ;   € > ' euros' ;
[^0-9][01]? { '$' > ' dollar' ;   '$' > ' dollars' ;
:: Null ;

# slugify
[^[:alnum:]&[:ascii:]]+ > '-' ;
:: Lower ;

# trim
[$] { '-' > &Remove() ;
'-' } [$] > &Remove() ;
RULES;

$tsl = Transliterator::createFromRules($rules, Transliterator::FORWARD);
$results = array_map(fn($s) => $tsl->transliterate($s), $strings);
print_r($results);

demo

不幸的是,PHP 手册完全没有关于 ICU 转换的内容,但您可以找到有关它们的信息 here

答案 9 :(得分:-1)

以下将用破折号代替空格。

$str = str_replace(' ', '-', $str);

然后,以下语句将删除除字母数字字符和破折号之外的所有内容。 (没有空格,因为在上一步中,我们用破折号代替了它们。

// Char representation     0 -  9   A-   Z   a-   z  -    
$str = preg_replace('/[^\x30-\x39\x41-\x5A\x61-\x7A\x2D]/', '', $str);

相当于

$str = preg_replace('/[^0-9A-Za-z-]+/', '', $str);

仅供参考:要删除字符串中的所有特殊字符,请使用

$str = preg_replace('/[^\x20-\x7E]/', '', $str); 

\ x20是Acsii字符开始的空间的十六进制,而\ x7E是波浪号。根据维基百科https://en.wikipedia.org/wiki/ASCII

可打印字符 代码20hex到7Ehex(称为可打印字符)代表字母,数字,标点符号和一些其他符号。总共有95个可打印字符。

相关问题