在PHP网站开发过程中会遇到很多需要转义的地方,下面推荐几个很好的函数,可以很好地增强网站的输入输出规范化问题。
1. 纯文本输出,适合input
function t($text){ $text = h($text); $text = strip_tags($text); return $text; }
2. 多行纯文本 适合textarea
function text($text) { return trim(nl2br(str_replace(' ', ' ', htmlspecialchars($text)))); }
3. 将html换行变成回车
function br2nl($text) { return trim(preg_replace('/<br\\s*\/?'.'>/i', '', $text)); }
4. 输出安全的html
function h($text){ $text = trim($text); $text = stripslashes($text); //完全过滤注释 $text = preg_replace('/<!--?.*-->/','',$text); //完全过滤动态代码 $text = preg_replace('/<\?|\?'.'>/','',$text); //完全过滤js $text = preg_replace('/<script?.*\/script>/','',$text); $text = str_replace('[','[',$text); $text = str_replace(']',']',$text); $text = str_replace('|','|',$text); //过滤换行符 $text = preg_replace('/\r?\n/','',$text); //br $text = preg_replace('/<br(\s\/)?'.'>/i','[br]',$text); $text = preg_replace('/(\[br\]\s*){10,}/i','[br]',$text); //hr img area input $text = preg_replace('/<(hr|img|input|area|isindex)( [^><\[\]]*)>/i','[\1\2]',$text); //过滤多余html $text = preg_replace('/<\/?(html|head|meta|link|base|body|title|style|script|form|iframe|frame|frameset)[^><]*>/i','',$text); //过滤on事件lang js while(preg_match('/(<[^><]+)( lang|onfinish|onmouse|onexit|onerror|onclick|onkey|onload|onchange|onfocus|onblur)[^><]+/i',$text,$mat)){ $text=str_replace($mat[0],$mat[1],$text); } while(preg_match('/(<[^><]+)(window\.|javascript:|js:|about:|file:|document\.|vbs:|cookie)([^><]*)/i',$text,$mat)){ $text=str_replace($mat[0],$mat[1].$mat[3],$text); } //过滤合法的html标签 while(preg_match('/<([a-z]+)[^><\[\]]*>[^><]*<\/\1>/i',$text,$mat)){ $text=str_replace($mat[0],str_replace('>',']',str_replace('<','[',$mat[0])),$text); } //转换引号 while(preg_match('/(\[[^\[\]]*=\s*)(\"|\')([^\2=\[\]]+)\2([^\[\]]*\])/i',$text,$mat)){ $text=str_replace($mat[0],$mat[1].'|'.$mat[3].'|'.$mat[4],$text); } //过滤错误的单个引号 while(preg_match('/\[[^\[\]]*(\"|\')[^\[\]]*\]/i',$text,$mat)){ $text=str_replace($mat[0],str_replace($mat[1],'',$mat[0]),$text); } //转换其它所有不合法的 < > $text = str_replace('<','<',$text); $text = str_replace('>','>',$text); $text = str_replace('"','"',$text); //反转换 $text = str_replace('[','<',$text); $text = str_replace(']','>',$text); $text = str_replace('|','"',$text); //过滤多余空格 $text = str_replace(' ',' ',$text); return $text; }
5. 过滤脚本代码
function cleanJs($text){ $text = trim($text); $text = stripslashes($text); //完全过滤动态代码 $text = preg_replace('/<\?|\?'.'>/','',$text); //完全过滤js $text = preg_replace('/<script?.*\/script>/','',$text); //过滤多余html $text = preg_replace('/<\/?(html|head|meta|link|base|body|title|style|script|form|iframe|frame|frameset)[^><]*>/i','',$text); //过滤on事件lang js while(preg_match('/(<[^><]+)(lang|onfinish|onmouse|onexit|onerror|onclick|onkey|onload|onchange|onfocus|onblur)[^><]+/i',$text,$mat)){ $text=str_replace($mat[0],$mat[1],$text); } while(preg_match('/(<[^><]+)(window\.|javascript:|js:|about:|file:|document\.|vbs:|cookie)([^><]*)/i',$text,$mat)){ $text=str_replace($mat[0],$mat[1].$mat[3],$text); } return $text; }
6. 在编辑器中显示纯文本
function et($text) { return trim(br2nl(str_replace(' ', ' ', $text ))); }
7. 在html编辑器中显示html
function eh($text) { return trim(str_replace('"','"', $text)); }
8. 判断时间距离
function friendlyDate($sTime,$type = 'normal',$alt = 'false') { //sTime=源时间,cTime=当前时间,dTime=时间差 $cTime = time(); $dTime = $cTime - $sTime; $dDay = intval(date("Ymd",$cTime)) - intval(date("Ymd",$sTime)); $dYear = intval(date("Y",$cTime)) - intval(date("Y",$sTime)); //normal:n秒前,n分钟前,n小时前,日期 if($type=='normal'){ if( $dTime < 60 ) { echo $dTime."秒前"; } elseif( $dTime < 3600 ) { echo intval($dTime/60)."分钟前"; } elseif( $dTime >= 3600 && $dDay == 0 ) { echo intval($dTime/3600)."小时前"; } elseif($dYear==0) { echo date("m-d ,H:i",$sTime); } else { echo date("Y-m-d ,H:i",$sTime); } //full: Y-m-d , H:i:s } elseif($type=='full') { echo date("Y-m-d , H:i:s",$sTime); } }
성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사
어 ass 신 크리드 그림자 : 조개 수수께끼 솔루션
3 몇 주 전ByDDD
Windows 11 KB5054979의 새로운 기능 및 업데이트 문제를 해결하는 방법
2 몇 주 전ByDDD
Atomfall에서 크레인 제어 키 카드를 찾을 수 있습니다
3 몇 주 전ByDDD
<s> : 데드 레일 - 모든 도전을 완료하는 방법
4 몇 주 전ByDDD
Atomfall Guide : 항목 위치, 퀘스트 가이드 및 팁
1 몇 달 전ByDDD

뜨거운 도구

SublimeText3 영어 버전
권장 사항: Win 버전, 코드 프롬프트 지원!

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

mPDF
mPDF는 UTF-8로 인코딩된 HTML에서 PDF 파일을 생성할 수 있는 PHP 라이브러리입니다. 원저자인 Ian Back은 자신의 웹 사이트에서 "즉시" PDF 파일을 출력하고 다양한 언어를 처리하기 위해 mPDF를 작성했습니다. HTML2FPDF와 같은 원본 스크립트보다 유니코드 글꼴을 사용할 때 속도가 느리고 더 큰 파일을 생성하지만 CSS 스타일 등을 지원하고 많은 개선 사항이 있습니다. RTL(아랍어, 히브리어), CJK(중국어, 일본어, 한국어)를 포함한 거의 모든 언어를 지원합니다. 중첩된 블록 수준 요소(예: P, DIV)를 지원합니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경
