天天看点

PHP正则正则表达式

正则表达式

常用元字符: \d :配一个数字 \w:匹配一个数字或字母字符  包括 a-z和A-Z 以及0-9 \s :匹配一个空白字符,包括空格 制表 换行 回车

^:表示一个串的开始位置 $:表示一个串的结束位置 ?:表示出现一次或零次 {n}:出现 n 次

preg_match($regex,$str) //用于判断字符串$str是否与正则表达式$regex匹配 匹配返回true 不匹配返回false      
preg_replace($regex,'$newstr',$str) //将字符串$str中与正则表达式$regex匹配的字符替换为$newstr 返回替换后的串
      
$regex = '/^\(?[2-9]\d{2}\)?[\-\s]\d{3}-\d{4}$/'; 
$str  = "(555) 123-1231";
echo preg_match($regex,$str); //输出 1
$regex = '/[\(\)\s\-]/';
echo preg_replace($regex,'',$str); // 输出 5551231231
      
有问题留言给我