本文實例總結了php字符串過濾與替換的方法。分享給大家供大家參考。具體實現方法如下:
復制代碼 代碼如下:<?php
class cls_string_filter{
//將\n轉化為<br/>--囧,這有意思麼?
static public function nl2br($string){
return nl2br($string);
}
//將<br/>轉化為\n
static public function br2nl($string){
$array = array('<br>','<br/>');
return str_replace($array,"\n",$string);//字符串替換
}
//多個空格只保留一個
static public function merge_spaces($string){
return preg_replace("/\s(?=\s)/","\\1",$string);//(?=pattern)舉例:abc(?=kk)能匹配abckk,但不能匹配abcdd
}
//多個<br/>只保留一個
static public function merge_brs($string){
return preg_replace("/((<br\/?>)+)/i","<br>",$string);//---"/"為什麼也轉義了
}
//過濾字符串中的html標簽
static public function strip_tags($string){
return strip_tags($string);
}
//將字符串轉換為小寫--/--大寫
static public function strtolower($string){
return strtolower($string);
}
static public function strtoupper($string){
return strtoupper($string);
}
//過濾字符串開頭與結尾的特定字符
static public function trim($string,$char_list='\\\\s'){
$find = array('/[\^\-\]\\\]/S','/\\\{4}/S','/\//');
$replace = array('\\\\\\0','\\','\/');
$char = preg_replace($fine,$replace,$char_list);
$pattern = '^['.$chars.']*|['.$chars.']';
return preg_replace("/$pattern/sSD",'',$string);
}
//過濾字符串中<style>腳本
static public function stric_style($string){
$reg = "/<style[^>]*?>.*?<\/style>/is";
return preg_replace($reg,'',$string);
}
//過濾字符串中html危險代碼
static public function strip_html_tags($string){
$reg = "/(\/?)/(script|iframe|style|html|body|title|meta|\?|\%)([^>]*?>)/is";
return preg_replace($reg,'',$string);
}
}
?>
希望本文所述對大家的php程序設計有所幫助。