正则表达式几乎在所有编程语言里面都会用到,本实例介绍php中正则表达式preg_match函数的应用。
preg_match() 函数用于进行正则表达式匹配,成功返回 1 ,否则返回 0 。
preg_match() 匹配成功一次后就会停止匹配,如果要实现全部结果的匹配,则需使用 preg_match_all() 函数。
语法:preg_match (pattern , subject, matches)参数描述
pattern正则表达式
subject需要匹配检索的对象
matches可选,存储匹配结果的数组
实例:
此实例匹配大写字母后面带有.和空格的字符串,只能匹配到J. ,因为preg_match() 匹配成功一次后就会停止匹配,后面不会再匹配了。
php$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. )