首頁 > 後端開發 > php教程 > PHP之正規函數

PHP之正規函數

WBOY
發布: 2016-07-28 08:27:13
原創
1033 人瀏覽過

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

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板