欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

php中str_replace替换实例讲解

程序员文章站 2022-04-05 12:51:04
...

在对于字符串的替换上,我们已经学过了不少的方法。但在做练习题的时候,我们会对多个字符串进行替换。从方法的实用性来说,str_replace就非常适合处理多个字符串的替换问题。下面我们就php中str_replace的概念、语法、参数、返回值进行讲解,然后带来替换的实例分享。

1、概念
str_replace() 函数以其他字符替换字符串中的一些字符(区分大小写)。

该函数区分大小写。请使用 str_ireplace() 函数执行不区分大小写的搜索。

2、语法
str_replace(find,replace,string,count)
3、参数
Find、replace、string、count

4、返回值
返回带有替换值的字符串或数组。

5、实例
创建一个PHP示例文件;然后通过“tr_replace($vowels, “”,”Hello World of PHP”);”方法替换多个字符串即可。
echo str_replace(array(“m”,”i”),array(“n”,”z”),”my name is jim!”)

  1. echo str_replace(array('m','i'),'n',"my name is jim!");
  2. $vowels = array("a", "e", "i", "o", "u", "A", "E", "I", "O", "U");
  3. $onlyconsonants = str_replace($vowels, "","Hello World of PHP");
  4. echo $onlyconsonants;

知识点扩展:

PHP利用str_replace防注入的方法
<?php
/**

  1. * 安全过滤函数
  2. *
  3. * @param $string
  4. * @return string
  5. */
  6. function safe_replace($string) {
  7. $string = str_replace('%20','',$string);
  8. $string = str_replace('%27','',$string);
  9. $string = str_replace('%2527','',$string);
  10. $string = str_replace('*','',$string);
  11. $string = str_replace('"','&quot;',$string);
  12. $string = str_replace("'",'',$string);
  13. $string = str_replace('"','',$string);
  14. $string = str_replace(';','',$string);
  15. $string = str_replace('<','&lt;',$string);
  16. $string = str_replace('>','&gt;',$string);
  17. $string = str_replace("{",'',$string);
  18. $string = str_replace('}','',$string);
  19. $string = str_replace('','',$string);
  20. return $string;
  21. }
  22. ?>
  23. <?php
  24. /**
  25. * 返回经addslashes处理过的字符串或数组
  26. * @param $string 需要处理的字符串或数组
  27. * @return mixed
  28. */
  29. function new_addslashes($string) {
  30. if(!is_array($string)) return addslashes($string);
  31. foreach($string as $key => $val) $string[$key] = new_addslashes($val);
  32. return $string;
  33. }
  34. ?>
  35. <?php
  36. //对请求的字符串进行安全处理
  37. /*
  38. $safestep
  39. 0 为不处理,
  40. 1 为禁止不安全HTML内容(javascript等),
  41. 2 完全禁止HTML内容,并替换部份不安全字符串(如:eval(、union、CONCAT(、--、等)
  42. */
  43. function StringSafe($str, $safestep=-1){
  44. $safestep = ($safestep > -1) ? $safestep : 1;
  45. if($safestep == 1){
  46. $str = preg_replace("#script:#i", "script:", $str);
  47. $str = preg_replace("#<[/]{0,1}(link|meta|ifr|fra|scr)[^>]*>#isU", '', $str);
  48. $str = preg_replace("#[ ]{1,}#", ' ', $str);
  49. return $str;
  50. }else if($safestep == 2){
  51. $str = addslashes(htmlspecialchars(stripslashes($str)));
  52. $str = preg_replace("#eval#i", 'eval', $str);
  53. $str = preg_replace("#union#i", 'union', $str);
  54. $str = preg_replace("#concat#i", 'concat', $str);
  55. $str = preg_replace("#--#", '--', $str);
  56. $str = preg_replace("#[ ]{1,}#", ' ', $str);
  57. return $str;
  58. }else{
  59. return $str;
  60. }
  61. }
  62. ?>
  63. <?php
  64. /**
  65. +----------------------------------------------------------
  66. * 输出安全的html,用于过滤危险代码
  67. +----------------------------------------------------------
  68. * @access public
  69. +----------------------------------------------------------
  70. * @param string $text 要处理的字符串
  71. * @param mixed $tags 允许的标签列表,如 table|td|th|td
  72. +----------------------------------------------------------
  73. * @return string
  74. +----------------------------------------------------------
  75. */
  76. static public function safeHtml($text, $tags = null)
  77. {
  78. $text = trim($text);
  79. //完全过滤注释
  80. $text = preg_replace('/<!--?.*-->/','',$text);
  81. //完全过滤动态代码
  82. $text = preg_replace('/<?|?'.'>/','',$text);
  83. //完全过滤js
  84. $text = preg_replace('/<script?.*/script>/','',$text);
  85. $text = str_replace('[','[',$text);
  86. $text = str_replace(']',']',$text);
  87. $text = str_replace('|','|',$text);
  88. //过滤换行符
  89. $text = preg_replace('/ ? /','',$text);
  90. //br
  91. $text = preg_replace('/<br(s/)?'.'>/i','[br]',$text);
  92. $text = preg_replace('/([br]s*){10,}/i','[br]',$text);
  93. //过滤危险的属性,如:过滤on事件lang js
  94. while(preg_match('/(<[^><]+)(lang|on|action|background|codebase|dynsrc|lowsrc)[^><]+/i',$text,$mat)){
  95. $text=str_replace($mat[0],$mat[1],$text);
  96. }
  97. while(preg_match('/(<[^><]+)(window.|javascript:|js:|about:|file:|document.|vbs:|cookie)([^><]*)/i',$text,$mat)){
  98. $text=str_replace($mat[0],$mat[1].$mat[3],$text);
  99. }
  100. if( empty($allowTags) ) { $allowTags = self::$htmlTags['allow']; }
  101. //允许的HTML标签
  102. $text = preg_replace('/<('.$allowTags.')( [^><[]]*)>/i','[12]',$text);
  103. //过滤多余html
  104. if ( empty($banTag) ) { $banTag = self::$htmlTags['ban']; }
  105. $text = preg_replace('/</?('.$banTag.')[^><]*>/i','',$text);
  106. //过滤合法的html标签
  107. while(preg_match('/<([a-z]+)[^><[]]*>[^><]*</1>/i',$text,$mat)){
  108. $text=str_replace($mat[0],str_replace('>',']',str_replace('<','[',$mat[0])),$text);
  109. }
  110. //转换引号
  111. while(preg_match('/([[^[]]*=s*)("|')([^2=[]]+)2([^[]]*])/i',$text,$mat)){
  112. $text=str_replace($mat[0],$mat[1].'|'.$mat[3].'|'.$mat[4],$text);
  113. }
  114. //空属性转换
  115. $text = str_replace('''','||',$text);
  116. $text = str_replace('""','||',$text);
  117. //过滤错误的单个引号
  118. while(preg_match('/[[^[]]*("|')[^[]]*]/i',$text,$mat)){
  119. $text=str_replace($mat[0],str_replace($mat[1],'',$mat[0]),$text);
  120. }
  121. //转换其它所有不合法的 < >
  122. $text = str_replace('<','&lt;',$text);
  123. $text = str_replace('>','&gt;',$text);
  124. $text = str_replace('"','&quot;',$text);
  125. //反转换
  126. $text = str_replace('[','<',$text);
  127. $text = str_replace(']','>',$text);
  128. $text = str_replace('|','"',$text);
  129. //过滤多余空格
  130. $text = str_replace(' ',' ',$text);
  131. return $text;
  132. }
  133. ?>
  134. <?php
  135. function RemoveXSS($val) {
  136. // remove all non-printable characters. CR(0a) and LF(0b) and TAB(9) are allowed
  137. // this prevents some character re-spacing such as <javascript>
  138. // note that you have to handle splits with , , and later since they *are* allowed in some // inputs
  139. $val = preg_replace('/([x00-x08,x0b-x0c,x0e-x19])/', '', $val);
  140. // straight replacements, the user should never need these since they're normal characters
  141. // this prevents like <IMG SRC=@avascript:alert('XSS')>
  142. $search = 'abcdefghijklmnopqrstuvwxyz';
  143. $search .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  144. $search .= '1234567890!@#$%^&*()';
  145. $search .= '~`";:?+/={}[]-_|'';
  146. for ($i = 0; $i < strlen($search); $i++) {
  147. // ;? matches the ;, which is optional
  148. // 0{0,7} matches any padded zeros, which are optional and go up to 8 chars
  149. // @ @ search for the hex values
  150. $val = preg_replace('/(&#[xX]0{0,8}'.dechex(ord($search[$i])).';?)/i', $search[$i], $val);//with a ;
  151. // @ @ 0{0,7} matches '0' zero to seven times
  152. $val = preg_replace('/(&#0{0,8}'.ord($search[$i]).';?)/', $search[$i], $val); // with a ;
  153. }
  154. // now the only remaining whitespace attacks are , , and
  155. $ra1 = Array('javascript', 'vbscript', 'expression', 'applet', 'meta', 'xml', 'blink', 'link', 'style', 'script', 'embed', 'object', 'iframe', 'frame', 'frameset', 'ilayer', 'layer', 'bgsound', 'title', 'base');
  156. $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');
  157. $ra = array_merge($ra1, $ra2);
  158. $found = true; // keep replacing as long as the previous round replaced something
  159. while ($found == true) {
  160. $val_before = $val;
  161. for ($i = 0; $i < sizeof($ra); $i++) {
  162. $pattern = '/';
  163. for ($j = 0; $j < strlen($ra[$i]); $j++) {
  164. if ($j > 0) {
  165. $pattern .= '(';
  166. $pattern .= '(&#[xX]0{0,8}([9ab]);)';
  167. $pattern .= '|';
  168. $pattern .= '|(&#0{0,8}([9|10|13]);)';
  169. $pattern .= ')*';
  170. }
  171. $pattern .= $ra[$i][$j];
  172. }
  173. $pattern .= '/i';
  174. $replacement = substr($ra[$i], 0, 2).'<x>'.substr($ra[$i], 2); // add in <> to nerf the tag
  175. $val = preg_replace($pattern, $replacement, $val); // filter out the hex tags
  176. if ($val_before == $val) {
  177. // no replacements were made, so exit the loop
  178. $found = false;
  179. }
  180. }
  181. }
  182. return $val;
  183. }
  184. ?>