PHP从string中删除特殊字符

我有删除特殊字符的问题。 我想删除除“()/。% – &”之外的所有特殊字符,因为我将该string设置为标题。

我编辑了原来的代码(看下面):

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

但是,这并不是要删除特殊字符,例如:“s”,“”,“ – ”等等。

原始代码:(这个工程,但它删除这些字符:“()/。% – &”)

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

你的网点匹配所有的字符。 将它(和其他特殊字符),如下所示:

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

不错的尝试! 我想你只需要做一些小的改变:

  • 将字符类中的方括号( [] )(也用[]表示)
  • 转义字符( \ )本身
  • 另外还有一个特殊的地方:如果它在两个字符之间,则意味着一个范围,但是如果它在开始或结束,则意味着文字-字符。

你会想要这样的东西:

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

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

你想strreplace ,因为性能明智便宜得多,仍然适合您的需求!

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

(除非这是关于安全性和sql注入的,否则,我宁愿使用一个允许的字符列表…更好,坚持经过testing,可靠的例程。)

顺便说一句,因为OP谈到了标题设置:我不会replace特殊的字符,但没有空间。 一个超级空间不是一个问题比两个单词粘在一起…

 <?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); ?> 
 preg_replace('/[^a-zA-Z0-9_ \-()\/%-&]/s', '', $String); 

看例子 。

 /** * 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 ); }