PHP 정규 함수

WBOY
WBOY원래의
2016-07-28 08:27:131032검색

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> } }</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]</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教程有兴趣的朋友有所帮助。

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.