Blogger Information
Blog 30
fans 1
comment 0
visits 23244
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
php中str_replace替换实例讲解
P粉896289085
Original
944 people have browsed it

这篇文章主要介绍了php中str_replace替换实例讲解内容,有需要的朋友们可以学习参考下。

在对于字符串的替换上,我们已经学过了不少的方法。但在做练习题的时候,我们会对多个字符串进行替换。从方法的实用性来说,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”);”方法替换多个字符串即可。

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

知识点扩展:

PHP利用str_replace防注入的方法

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

到此这篇关于php中str_replace替换实例讲解的文章就介绍到这了。

Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post