PHP之正则函数

WBOY
发布: 2016-07-28 08:27:13
原创
1025 人浏览过

php与javascript一样,正则的匹配内容通常用 / / 包起来,也可以使用其它非字母与数字起到同样作用,不能使用 \ \
$preg = ‘/ demo /’;


preg_match

<code><span><?php </span><span>$str</span> = <span>"abcdefgabcdbc"</span>;

    <span>$pattern</span> = <span>'/[da]bc/'</span>;
    <span>echo</span><span>'preg_match:'</span>.preg_match(<span>$pattern</span>, <span>$str</span>).<span>'<br>'</span>;

    <span>echo</span><span>'preg_match_all:'</span>.preg_match_all(<span>$pattern</span>, <span>$str</span>,<span>$matches</span>).<span>'<br>'</span>;

    <span>//preg_match_all匹配所有,并将其匹配项带入第三个参数 $matches</span>
    var_dump(<span>$matches</span>);
 <span>?></span><span>//</span>
preg_match:<span>1</span>
preg_match_all:<span>3</span><span>array</span>(<span>1</span>) { [<span>0</span>]=> <span>array</span>(<span>3</span>) { [<span>0</span>]=> string(<span>3</span>) <span>"abc"</span> [<span>1</span>]=> string(<span>3</span>) <span>"abc"</span> [<span>2</span>]=> string(<span>3</span>) <span>"dbc"</span> } }</span></code>
登录后复制

preg_replace

<code><span><span><?php </span><span>$str</span> = <span>'2014-11-25'</span>;
    <span>//使用()包括起来代表一个单元,可以与${n}对应使用,匹配的第几个内容会带入对应的${n}</span><span>$preg</span> = <span>'/(-)/'</span>;
    <span>$temp</span> = <span>'Year'</span>;
    <span>echo</span> preg_replace(<span>$preg</span>,<span>$temp</span>.<span>'${1}'</span>,<span>$str</span>);

    <span>echo</span><span>'<br>'</span>;

    <span>$preg</span> = <span>array</span>(
        <span>'/(\d+)/'</span>
    );
    <span>$temp</span> = <span>array</span>(
        <span>'temp[${1}]'</span>
    );
    <span>echo</span> preg_replace(<span>$preg</span>,<span>$temp</span>,<span>$str</span>);
<span>?></span></span>
//
2014Year-11Year-25
temp[2014]-temp[11]-temp[25]</span></code>
登录后复制

preg_split

<code><span><span><?php </span><span>$str</span> = <span>'1+2-3/4*5'</span>;
<span>$pattern</span> = <span>'#[+-/*]#'</span>;
<span>$res</span> = preg_split(<span>$pattern</span>,<span>$str</span>);
print_r(<span>$res</span>);
<span>//</span><span>Array</span> ( [<span>0</span>] => <span>1</span> [<span>1</span>] => <span>2</span> [<span>2</span>] => <span>3</span> [<span>3</span>] => <span>4</span> [<span>4</span>] => <span>5</span> )</span></span></code>
登录后复制
').addClass('pre-numbering').hide(); $(this).addClass('has-numbering').parent().append($numbering); for (i = 1; i ').text(i)); }; $numbering.fadeIn(1700); }); });

以上就介绍了 PHP之正则函数,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。

相关标签:
来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板