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