Home > Backend Development > PHP Tutorial > Regular expressions in PHP replace, filter, grep

Regular expressions in PHP replace, filter, grep

WBOY
Release: 2016-07-29 09:00:08
Original
1077 people have browsed it

<code> - preg\_replace( \$pattern,\$replacement,\$subject),preg\_filter ( \$pattern,\$replacement,\$subject);
 preg\_replace 和preg\_filter 将匹配到的数值进行替换,可以使用数组替换;
\ $replacement 将匹配到的值替换为这个变量中存放的值;
 \$pattern正则表达式;
 \$subject返回结果;
</code>
Copy after login

区别:

<code><span><span>function</span><span>show</span><span>(<span>$var</span> = null)</span>{</span><span>if</span>(<span>empty</span>(<span>$var</span>)){
        <span>echo</span><span>'null'</span>;
    }<span>elseif</span>(is_array(<span>$var</span>)||is_object(<span>$var</span>)){
        <span>echo</span><span>'<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">'
Copy after login
Copy after login
; print_r($var); echo'
'
Copy after login
; }else { echo$var; } } //preg_replace,preg_filter//$pattern = '/[0-9]/';//字符串$pattern = array('/[0123]/','/[456]/','/[789]/');//数组//$subject = 'y1jp78yn16ww55j9';//是字符串,使用$pattern和$replacement作了一次匹配替换$subject = array('y','1jp78','yn','16ww','55j9');//把$subject字符串任意拆分成好几段,放在$subject数组中,对数组中的每个值都做一次匹配替换//$replacement = '慕女神';//当$subject匹配到结果后要替换的变量$replacement = array('慕','女','神'); $str1 = preg_replace($pattern,$replacement,$subject);//保留所有字符串$str2 = preg_filter($pattern,$replacement,$subject);//只会保留发生了替换的字符串 show($str1); echo'
'
; show($str2);

结果:
Regular expressions in PHP replace, filter, grep

结论:

<code>preg\_replace在数组匹配中会输出未发生匹配的字段;
preg\_filter 在数组匹配中不会输出未发生匹配的字段;
</code>
Copy after login
  • preg_grep($pattern,array $input)
    功能与preg_filter 相似,只匹配不替换而且只返回发生匹配的字符串或数组,可以起一个过滤作用,过滤掉preg_filter不替换的符串或数组。
').addClass('pre-numbering').hide(); $(this).addClass('has-numbering').parent().append($numbering); for (i = 1; i ').text(i)); }; $numbering.fadeIn(1700); }); });

以上就介绍了Regular expressions in PHP replace, filter, grep,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template