php中str_replace替换实例讲解

时间:2021-12-12 16:22:29

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

1、概念

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

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

2、语法

?
1
str_replace(find,replace,string,count)

3、参数

Find、replace、string、count

4、返回值

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

5、实例

创建一个PHP示例文件;然后通过“tr_replace($vowels, "","Hello World of PHP");”方法替换多个字符串即可。

?
1
2
3
4
5
6
7
8
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;

知识点扩展:

PHP利用str_replace防注入的方法

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
   <?php
    /**
    * 安全过滤函数
    *
    * @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('"','&quot;',$string);
    $string = str_replace("'",'',$string);
    $string = str_replace('"','',$string);
    $string = str_replace(';','',$string);
    $string = str_replace('<','&lt;',$string);
    $string = str_replace('>','&gt;',$string);
    $string = str_replace("{",'',$string);
    $string = str_replace('}','',$string);
    $string = str_replace('','',$string);
    return $string;
    }
    ?>
 
    <?php
    /**
    * 返回经addslashes处理过的字符串或数组
    * @param $string 需要处理的字符串或数组
    * @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
    //对请求的字符串进行安全处理
    /*
    $safestep
    0 为不处理,
    1 为禁止不安全HTML内容(javascript等),
    2 完全禁止HTML内容,并替换部份不安全字符串(如: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,用于过滤危险代码
        +----------------------------------------------------------
        * @access public
        +----------------------------------------------------------
        * @param string $text 要处理的字符串
        * @param mixed $tags 允许的标签列表,如 table|td|th|td
        +----------------------------------------------------------
        * @return string
        +----------------------------------------------------------
        */
       static public function safeHtml($text, $tags = null)
       {
           $text =  trim($text);
           //完全过滤注释
           $text = preg_replace('/<!--?.*-->/','',$text);
           //完全过滤动态代码
           $text =  preg_replace('/<?|?'.'>/','',$text);
           //完全过滤js
           $text = preg_replace('/<script?.*/script>/','',$text);
           $text str_replace('[','&#091;',$text);
           $text = str_replace(']','&#093;',$text);
           $text str_replace('|','&#124;',$text);
           //过滤换行符
           $text = preg_replace('/ ? /','',$text);
           //br
           $text =  preg_replace('/<br(s/)?'.'>/i','[br]',$text);
           $text = preg_replace('/([br]s*){10,}/i','[br]',$text);
           //过滤危险的属性,如:过滤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标签
           $text =  preg_replace('/<('.$allowTags.')( [^><[]]*)>/i','[12]',$text);
           //过滤多余html
           if ( empty($banTag) ) { $banTag = self::$htmlTags['ban']; }
           $text =  preg_replace('/</?('.$banTag.')[^><]*>/i','',$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);
           }
           //空属性转换
           $text str_replace('''','||',$text);
           $text = str_replace('""','||',$text);
           //过滤错误的单个引号
           while(preg_match('/[[^[]]*("|')[^[]]*]/i',$text,$mat)){
               $text=str_replace($mat[0],str_replace($mat[1],'',$mat[0]),$text);
           }
           //转换其它所有不合法的 < >
           $text str_replace('<','&lt;',$text);
           $text = str_replace('>','&gt;',$text);
           $text = str_replace('"','&quot;',$text);
           //反转换
           $text str_replace('[','<',$text);
           $text str_replace(']','>',$text);
           $text str_replace('|','"',$text);
           //过滤多余空格
           $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{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{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;
    }
    ?>

到此这篇关于php中str_replace替换实例讲解的文章就介绍到这了,更多相关php中str_replace如何替换内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://www.py.cn/php/jiaocheng/23792.html