PHP 从字符串中删除特殊字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6073221/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 23:16:41  来源:igfitidea点击:

PHP remove special character from string

phpregexstringpreg-replace

提问by user453089

I have problems with removing special characters. I want to remove all special characters except "( ) / . % - &", because I'm setting that string as a title.

我在删除特殊字符时遇到问题。我想删除除“( ) / . % - &”之外的所有特殊字符,因为我将该字符串设置为标题。

I edited code from the original (look below):

我编辑了原始代码(请看下面):

preg_replace('/[^a-zA-Z0-9_ -%][().][\/]/s', '', $String);

But this is not working to remove special characters like: "a?s, "a?", "a", among others.

但这并不能删除特殊字符,例如:“a?s、“a?”、“a”等。

original code: (this works but it removes these characters: "( ) / . % - &")

原始代码:(这有效,但它删除了这些字符:“( ) / . % - &”)

preg_replace('/[^a-zA-Z0-9_ -]/s', '', $String);

回答by Luke Sneeringer

Your dot is matching all characters. Escape it (and the other special characters), like this:

您的点匹配所有字符。转义它(和其他特殊字符),如下所示:

preg_replace('/[^a-zA-Z0-9_ %\[\]\.\(\)%&-]/s', '', $String);

回答by Thomas Hupkens

preg_replace('#[^\w()/.%\-&]#',"",$string);

回答by Anonymoose

Good try! I think you just have to make a few small changes:

很好的尝试!我认为你只需要做一些小的改变:

  • Escape the square brackets ([and ]) inside the character class (which are also indicated by [and ])
  • Escape the escape character (\) itself
  • Plus there's a quirk where -is special: if it's between two characters, it means a range, but if it's at the beginning or the end, it means the literal -character.
  • 转义字符类中的方括号([])(也由[和表示]
  • 转义转义字符 ( \) 本身
  • 另外还有一个-特殊之处:如果它在两个字符之间,则表示范围,但如果它在开头或结尾,则表示文字-字符。

You'll want something like this:

你会想要这样的东西:

preg_replace('/[^a-zA-Z0-9_%\[().\]\/-]/s', '', $String);

See http://docs.activestate.com/activeperl/5.10/lib/pods/perlrecharclass.html#special_characters_inside_a_bracketed_character_classif you want to read up further on this topic.

如果您想进一步阅读此主题,请参阅http://docs.activestate.com/activeperl/5.10/lib/pods/perlrecharclass.html#special_characters_inside_a_bracketed_character_class

回答by Frank Nocke

You want str replace, because performance-wise it's muchcheaper and still fits your needs!

你希望海峡更换,因为性能方面它是便宜,仍然适合您的需要!

$title = str_replace( array( '\'', '"', ',' , ';', '<', '>' ), ' ', $rawtitle);

(Unless this is all about security and sql injection, in that case, I'd rather to go with a POSITIVE list of ALLOWED characters... even better, stick with tested, proven routines.)

(除非这完全是关于安全性和 sql 注入,在这种情况下,我宁愿使用 ALLOWED 字符的 POSITIVE 列表......更好的是,坚持使用经过测试的、经过验证的例程。)

Btw, since the OP talked about title-setting: I wouldn't replace special chars with nothing, but with a space. A superficious space is less of a problem than two words glued together...

顺便说一句,由于 OP 谈到了标题设置:我不会用任何东西替换特殊字符,而是用空格替换。一个肤浅的空间比两个词粘在一起更不是问题......

回答by dinhhiepdung

<?php
$string = '`~!@#$%^&^&*()_+{}[]|\/;:"< >,.?-<h1>You .</h1><p> text</p>'."'";
$string=strip_tags($string,"");
$string = preg_replace('/[^A-Za-z0-9\s.\s-]/','',$string); 
echo $string = str_replace( array( '-', '.' ), '', $string);
?>

回答by Alex

preg_replace('/[^a-zA-Z0-9_ \-()\/%-&]/s', '', $String);

回答by TechyFlick

mysqli_set_charset($con,"utf8");
$title = ' LEVEL a“ EXTENDED'; 
$newtitle = preg_replace('/[^(\x20-\x7F)]*/','', $title);     
echo $newtitle;

Result :  LEVEL EXTENDED

Many Strange Character be removed by applying below the mysql connection code. but in some circumstances of removing this type strange character like a you can use preg_replace above format.

通过在mysql连接代码下方应用,可以删除许多奇怪的字符。但是在某些情况下,您可以使用 preg_replace 上面的格式删除这种类型的奇怪字符。

回答by binkute

See example.

参见示例

/**
 * nv_get_plaintext()
 *
 * @param mixed $string
 * @return
 */
function nv_get_plaintext( $string, $keep_image = false, $keep_link = false )
{
    // Get image tags
    if( $keep_image )
    {
        if( preg_match_all( "/\<img[^\>]*src=\"([^\"]*)\"[^\>]*\>/is", $string, $match ) )
        {
            foreach( $match[0] as $key => $_m )
            {
                $textimg = '';
                if( strpos( $match[1][$key], 'data:image/png;base64' ) === false )
                {
                    $textimg = " " . $match[1][$key];
                }
                if( preg_match_all( "/\<img[^\>]*alt=\"([^\"]+)\"[^\>]*\>/is", $_m, $m_alt ) )
                {
                    $textimg .= " " . $m_alt[1][0];
                }
                $string = str_replace( $_m, $textimg, $string );
            }
        }
    }

    // Get link tags
    if( $keep_link )
    {
        if( preg_match_all( "/\<a[^\>]*href=\"([^\"]+)\"[^\>]*\>(.*)\<\/a\>/isU", $string, $match ) )
        {
            foreach( $match[0] as $key => $_m )
            {
                $string = str_replace( $_m, $match[1][$key] . " " . $match[2][$key], $string );
            }
        }
    }

    $string = str_replace( '?', ' ', strip_tags( $string ) );
    return preg_replace( '/[ ]+/', ' ', $string );
}