php中str_replace替換實(shí)例講解
在對(duì)于字符串的替換上,我們已經(jīng)學(xué)過(guò)了不少的方法。但在做練習(xí)題的時(shí)候,我們會(huì)對(duì)多個(gè)字符串進(jìn)行替換。從方法的實(shí)用性來(lái)說(shuō),str_replace就非常適合處理多個(gè)字符串的替換問(wèn)題。下面我們就php中str_replace的概念、語(yǔ)法、參數(shù)、返回值進(jìn)行講解,然后帶來(lái)替換的實(shí)例分享。
1、概念
str_replace() 函數(shù)以其他字符替換字符串中的一些字符(區(qū)分大小寫(xiě))。
該函數(shù)區(qū)分大小寫(xiě)。請(qǐng)使用 str_ireplace() 函數(shù)執(zhí)行不區(qū)分大小寫(xiě)的搜索。
2、語(yǔ)法
str_replace(find,replace,string,count)
3、參數(shù)
Find、replace、string、count
4、返回值
返回帶有替換值的字符串或數(shù)組。
5、實(shí)例
創(chuàng)建一個(gè)PHP示例文件;然后通過(guò)“tr_replace($vowels, "","Hello World of PHP");”方法替換多個(gè)字符串即可。
echo str_replace(array("m","i"),array("n","z"),"my name is jim!")
echo str_replace(array('m','i'),'n',"my name is jim!");
$vowels = array("a", "e", "i", "o", "u", "A", "E", "I", "O", "U");
$onlyconsonants = str_replace($vowels, "","Hello World of PHP");
echo $onlyconsonants;
知識(shí)點(diǎn)擴(kuò)展:
PHP利用str_replace防注入的方法
<?php
/**
* 安全過(guò)濾函數(shù)
*
* @param $string
* @return string
*/
function safe_replace($string) {
$string = str_replace('%20','',$string);
$string = str_replace('%27','',$string);
$string = str_replace('%2527','',$string);
$string = str_replace('*','',$string);
$string = str_replace('"','"',$string);
$string = str_replace("'",'',$string);
$string = str_replace('"','',$string);
$string = str_replace(';','',$string);
$string = str_replace('<','<',$string);
$string = str_replace('>','>',$string);
$string = str_replace("{",'',$string);
$string = str_replace('}','',$string);
$string = str_replace('','',$string);
return $string;
}
?>
<?php
/**
* 返回經(jīng)addslashes處理過(guò)的字符串或數(shù)組
* @param $string 需要處理的字符串或數(shù)組
* @return mixed
*/
function new_addslashes($string) {
if(!is_array($string)) return addslashes($string);
foreach($string as $key => $val) $string[$key] = new_addslashes($val);
return $string;
}
?>
<?php
//對(duì)請(qǐng)求的字符串進(jìn)行安全處理
/*
$safestep
0 為不處理,
1 為禁止不安全HTML內(nèi)容(javascript等),
2 完全禁止HTML內(nèi)容,并替換部份不安全字符串(如:eval(、union、CONCAT(、--、等)
*/
function StringSafe($str, $safestep=-1){
$safestep = ($safestep > -1) ? $safestep : 1;
if($safestep == 1){
$str = preg_replace("#script:#i", "script:", $str);
$str = preg_replace("#<[/]{0,1}(link|meta|ifr|fra|scr)[^>]*>#isU", '', $str);
$str = preg_replace("#[ ]{1,}#", ' ', $str);
return $str;
}else if($safestep == 2){
$str = addslashes(htmlspecialchars(stripslashes($str)));
$str = preg_replace("#eval#i", 'eval', $str);
$str = preg_replace("#union#i", 'union', $str);
$str = preg_replace("#concat#i", 'concat', $str);
$str = preg_replace("#--#", '--', $str);
$str = preg_replace("#[ ]{1,}#", ' ', $str);
return $str;
}else{
return $str;
}
}
?>
<?php
/**
+----------------------------------------------------------
* 輸出安全的html,用于過(guò)濾危險(xiǎn)代碼
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $text 要處理的字符串
* @param mixed $tags 允許的標(biāo)簽列表,如 table|td|th|td
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
static public function safeHtml($text, $tags = null)
{
$text = trim($text);
//完全過(guò)濾注釋
$text = preg_replace('/<!--?.*-->/','',$text);
//完全過(guò)濾動(dòng)態(tài)代碼
$text = preg_replace('/<?|?'.'>/','',$text);
//完全過(guò)濾js
$text = preg_replace('/<script?.*/script>/','',$text);
$text = str_replace('[','[',$text);
$text = str_replace(']',']',$text);
$text = str_replace('|','|',$text);
//過(guò)濾換行符
$text = preg_replace('/ ? /','',$text);
//br
$text = preg_replace('/<br(s/)?'.'>/i','[br]',$text);
$text = preg_replace('/([br]s*){10,}/i','[br]',$text);
//過(guò)濾危險(xiǎn)的屬性,如:過(guò)濾on事件lang js
while(preg_match('/(<[^><]+)(lang|on|action|background|codebase|dynsrc|lowsrc)[^><]+/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);
}
if( empty($allowTags) ) { $allowTags = self::$htmlTags['allow']; }
//允許的HTML標(biāo)簽
$text = preg_replace('/<('.$allowTags.')( [^><[]]*)>/i','[12]',$text);
//過(guò)濾多余html
if ( empty($banTag) ) { $banTag = self::$htmlTags['ban']; }
$text = preg_replace('/</?('.$banTag.')[^><]*>/i','',$text);
//過(guò)濾合法的html標(biāo)簽
while(preg_match('/<([a-z]+)[^><[]]*>[^><]*</1>/i',$text,$mat)){
$text=str_replace($mat[0],str_replace('>',']',str_replace('<','[',$mat[0])),$text);
}
//轉(zhuǎn)換引號(hào)
while(preg_match('/([[^[]]*=s*)("|')([^2=[]]+)2([^[]]*])/i',$text,$mat)){
$text=str_replace($mat[0],$mat[1].'|'.$mat[3].'|'.$mat[4],$text);
}
//空屬性轉(zhuǎn)換
$text = str_replace('''','||',$text);
$text = str_replace('""','||',$text);
//過(guò)濾錯(cuò)誤的單個(gè)引號(hào)
while(preg_match('/[[^[]]*("|')[^[]]*]/i',$text,$mat)){
$text=str_replace($mat[0],str_replace($mat[1],'',$mat[0]),$text);
}
//轉(zhuǎn)換其它所有不合法的 < >
$text = str_replace('<','<',$text);
$text = str_replace('>','>',$text);
$text = str_replace('"','"',$text);
//反轉(zhuǎn)換
$text = str_replace('[','<',$text);
$text = str_replace(']','>',$text);
$text = str_replace('|','"',$text);
//過(guò)濾多余空格
$text = str_replace(' ',' ',$text);
return $text;
}
?>
<?php
function RemoveXSS($val) {
// remove all non-printable characters. CR(0a) and LF(0b) and TAB(9) are allowed
// this prevents some character re-spacing such as <javascript>
// note that you have to handle splits with , , and later since they *are* allowed in some // inputs
$val = preg_replace('/([x00-x08,x0b-x0c,x0e-x19])/', '', $val);
// straight replacements, the user should never need these since they're normal characters
// this prevents like <IMG SRC=@avascript:alert('XSS')>
$search = 'abcdefghijklmnopqrstuvwxyz';
$search .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
$search .= '1234567890!@#$%^&*()';
$search .= '~`";:?+/={}[]-_|'';
for ($i = 0; $i < strlen($search); $i++) {
// ;? matches the ;, which is optional
// 0{0,7} matches any padded zeros, which are optional and go up to 8 chars
// @ @ search for the hex values
$val = preg_replace('/(&#[xX]0{0,8}'.dechex(ord($search[$i])).';?)/i', $search[$i], $val);//with a ;
// @ @ 0{0,7} matches '0' zero to seven times
$val = preg_replace('/(�{0,8}'.ord($search[$i]).';?)/', $search[$i], $val); // with a ;
}
// now the only remaining whitespace attacks are , , and
$ra1 = Array('javascript', 'vbscript', 'expression', 'applet', 'meta', 'xml', 'blink', 'link', 'style', 'script', 'embed', 'object', 'iframe', 'frame', 'frameset', 'ilayer', 'layer', 'bgsound', 'title', 'base');
$ra2 = Array('onabort', 'onactivate', 'onafterprint', 'onafterupdate', 'onbeforeactivate', 'onbeforecopy', 'onbeforecut', 'onbeforedeactivate', 'onbeforeeditfocus', 'onbeforepaste', 'onbeforeprint', 'onbeforeunload', 'onbeforeupdate', 'onblur', 'onbounce', 'oncellchange', 'onchange', 'onclick', 'oncontextmenu', 'oncontrolselect', 'oncopy', 'oncut', 'ondataavailable', 'ondatasetchanged', 'ondatasetcomplete', 'ondblclick', 'ondeactivate', 'ondrag', 'ondragend', 'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 'ondrop', 'onerror', 'onerrorupdate', 'onfilterchange', 'onfinish', 'onfocus', 'onfocusin', 'onfocusout', 'onhelp', 'onkeydown', 'onkeypress', 'onkeyup', 'onlayoutcomplete', 'onload', 'onlosecapture', 'onmousedown', 'onmouseenter', 'onmouseleave', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'onmousewheel', 'onmove', 'onmoveend', 'onmovestart', 'onpaste', 'onpropertychange', 'onreadystatechange', 'onreset', 'onresize', 'onresizeend', 'onresizestart', 'onrowenter', 'onrowexit', 'onrowsdelete', 'onrowsinserted', 'onscroll', 'onselect', 'onselectionchange', 'onselectstart', 'onstart', 'onstop', 'onsubmit', 'onunload');
$ra = array_merge($ra1, $ra2);
$found = true; // keep replacing as long as the previous round replaced something
while ($found == true) {
$val_before = $val;
for ($i = 0; $i < sizeof($ra); $i++) {
$pattern = '/';
for ($j = 0; $j < strlen($ra[$i]); $j++) {
if ($j > 0) {
$pattern .= '(';
$pattern .= '(&#[xX]0{0,8}([9ab]);)';
$pattern .= '|';
$pattern .= '|(�{0,8}([9|10|13]);)';
$pattern .= ')*';
}
$pattern .= $ra[$i][$j];
}
$pattern .= '/i';
$replacement = substr($ra[$i], 0, 2).'<x>'.substr($ra[$i], 2); // add in <> to nerf the tag
$val = preg_replace($pattern, $replacement, $val); // filter out the hex tags
if ($val_before == $val) {
// no replacements were made, so exit the loop
$found = false;
}
}
}
return $val;
}
?>
到此這篇關(guān)于php中str_replace替換實(shí)例講解的文章就介紹到這了,更多相關(guān)php中str_replace如何替換內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
PHP 下載文件時(shí)自動(dòng)添加bom頭的方法實(shí)例
這篇文章主要介紹了PHP 下載文件時(shí)自動(dòng)添加bom頭的方法實(shí)例,有需要的朋友可以參考一下2014-01-01
PHP數(shù)據(jù)的提交與過(guò)濾基本操作實(shí)例詳解
這篇文章主要介紹了PHP數(shù)據(jù)的提交與過(guò)濾基本操作,簡(jiǎn)要說(shuō)明了php數(shù)據(jù)過(guò)濾的基本方法并結(jié)合實(shí)例形式分析了php針對(duì)各種常見(jiàn)類型數(shù)據(jù)的過(guò)濾操作使用技巧,需要的朋友可以參考下2016-11-11
PHP后期靜態(tài)綁定之self::限制實(shí)例分析
這篇文章主要介紹了PHP后期靜態(tài)綁定之self::限制,結(jié)合實(shí)例形式分析了php后期靜態(tài)綁定self::與static相關(guān)使用技巧,需要的朋友可以參考下2018-12-12
php實(shí)現(xiàn)遞歸抓取網(wǎng)頁(yè)類實(shí)例
這篇文章主要介紹了php實(shí)現(xiàn)遞歸抓取網(wǎng)頁(yè)類,實(shí)例分析了php遞歸操作及網(wǎng)頁(yè)抓取的技巧,非常具有實(shí)用價(jià)值,需要的朋友可以參考下2015-04-04
通過(guò)PHP CLI實(shí)現(xiàn)簡(jiǎn)單的數(shù)據(jù)庫(kù)實(shí)時(shí)監(jiān)控調(diào)度
繼續(xù)CLI模式試驗(yàn),這次通過(guò)使用之前的“帶延時(shí)的死循環(huán)”方法,來(lái)實(shí)現(xiàn)個(gè)簡(jiǎn)單的數(shù)據(jù)庫(kù)實(shí)時(shí)監(jiān)控調(diào)度功能。2009-07-07
PHP獲取一年中每個(gè)星期的開(kāi)始和結(jié)束日期的方法
這篇文章主要介紹了PHP獲取一年中每個(gè)星期的開(kāi)始和結(jié)束日期的方法,涉及php對(duì)日期操作的技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-02-02

