正则函数:
1.字符串的匹配与查找
preg_match();
preg_match匹配一次
<?php
$str="linux and php and linux and java and html5";
$ptn='/linux/';
preg_match($ptn,$str,$arr);
echo '<pre>';
print_r($arr);
echo '</pre>';
?>
**
Array
(
[0] => linux
)
preg_match_all();
preg_match_all逐行匹配
<?php
$str="linux and php and linux and java and html5";
$ptn='/linux/';
preg_match_all($ptn,$str,$arr);
echo '<pre>';
print_r($arr);
echo '</pre>';
?>
**
Array
(
[0] => Array
(
[0] => linux
[1] => linux
)
)
preg_grep();
preg_grep数组搜索
<?php
$arr=array(
'title1'=>'linux is very much!',
'title2'=>'php is very much!',
'title3'=>'java and pap is very much!',
'title4'=>'html5 is and pxp very much!',
'title5'=>'javascript and linux is very much!',
'title6'=>'css3 and js and php and java is very much!'
);
$ptn='/p.p/';
$arr2=preg_grep($ptn,$arr);
echo '<pre>';
print_r($arr2);
echo '</pre>';
?>
**
Array
(
[title2] => php is very much!
[title3] => java and pap is very much!
[title4] => html5 is and pxp very much!
[title6] => css3 and js and php and java is very much!
)
2.字符串的替换
preg_replace();
**
<?php
$str='linux and php and Linux';
$ptn='/linux/i';
$rep='LINUX';
echo preg_replace($ptn,$rep,$str);
?>
**
LINUX and php and LINUX
3.字符串的分割与连接
preg_split();
**
<?php
$str='linux-and+php,and.Linux';
$ptn='/-|\+|,|\./';
$arr=preg_split($ptn,$str);
echo '<pre>';
print_r($arr);
echo '</pre>';
?>
**
Array
(
[0] => linux
[1] => and
[2] => php
[3] => and
[4] => Linux
)
本文详细介绍PHP中正则表达式的应用,包括字符串的匹配、查找、替换、分割与连接等操作,通过实例展示了preg_match、preg_match_all、preg_grep、preg_replace和preg_split函数的使用方法。
1134

被折叠的 条评论
为什么被折叠?



