先介绍preg_match函数的使用实例:
preg_match() 函数用于进行正则表达式匹配,成功返回 1 ,否则返回 0 。
preg_match() 匹配成功一次后就会停止匹配,如果要实现全部结果的匹配,则需使用 preg_match_all() 函数。
语法:
preg_match (pattern , subject, matches)
参数
描述
pattern
正则表达式
subject
需要匹配检索的对象
matches
可选,存储匹配结果的数组
实例:
此实例匹配大写字母后面带有.和空格的字符串,只能匹配到J. ,因为preg_match() 匹配成功一次后就会停止匹配,后面不会再匹配了。
$str="Daniel J. Gross Catholic High School A. is a faith and family based community committed to developing Christian leaders through educational excellence in the Marianist tradition.";
if(preg_match("/[A-Z]. /",$str,$matches)){
print_r($matches);
}
?>
输出结果:
Array ( [0] => J. )
preg_match_all函数的使用实例:
preg_match_all() 函数用于执行一个全局正则表达式匹配。
preg_match_all() 将实现全部结果的匹配,如果要匹配成功一次后停止匹配,请使用 preg_match() 函数。
语法:
preg_match_all (pattern , subject, matches)
参数
描述
pattern
正则表达式
subject
进行匹配的字符串
matches
所有匹配结果(数组)
实例:
$userinfo = "Name: John Poul
Title: PHP Guru";
preg_match_all ("/(.*)/U", $userinfo, $pat_array);
print $pat_array[0][0]."
".$pat_array[0][1]."\n";
?>
输出结果:
John Poul
PHP Guru