preg_match()和preg_match_all()

preg_match() 返回pattern
的匹配次数。 它的值将是0次(不匹配)或1次,因为 preg_match() 在第一次匹配后 将会停止搜索。preg_match_all()不同于此,它会一直搜索subject直到到达结尾。 如果发生错误 preg_match() 返回 **FALSE
preg_match()
preg_match() 函数用于进行正则表达式匹配,成功返回 1 ,否则返回 0 。
int preg_match( string pattern, string subject [, array matches ] )

if(preg_match("/php/i", "PHP is the web scripting language of choice.", $matches)){ print "A match was found:". $matches[0]; } else { print "A match was not found."; A match was found: PHP preg_match() 第一次匹配成功后就会停止匹配,如果要实现全部结果的匹配,即搜索到subject结尾处,则需使用 preg_match_all() 函数。

// 从 URL 中取得主机名 preg_match("/^(http://)?([^/]+)/i","http://www.jb51.net/index.html", $matches); $host = $matches[2]; // 从主机名中取得后面两段 preg_match("/[^./]+\.[^./]+$/", $host, $matches); echo "域名为:{$matches[0]}"; 域名为:jb51.net

preg_match_all()
preg_match_all() 函数用于进行正则表达式全局匹配,成功返回整个模式匹配的次数(可能为零),如果出错返回 FALSE 。
int preg_match_all( string pattern, string subject, array matches [, int flags ] )

$str = "<pre>学习php是一件快乐的事。</pre><pre>所有的phper需要共同努力!</pre>"; $kw = "php"; preg_match_all('/<pre>([\s\S]*?)<\/pre>/',$str,$mat); for($i=0;$i<count($mat[0]);$i++){ $mat[0][$i] = $mat[1][$i]; $mat[0][$i] = str_replace($kw, '<span style="color:#ff0000">'.$kw.'</span>', $mat[0][$i]); $str = str_replace($mat[1][$i], $mat[0][$i], $str); echo $str;

正则匹配中文汉字
正则匹配中文汉字根据页面编码不同而略有区别:
•GBK/GB2312编码:[x80-xff>]+ 或 [xa1-xff]+
•UTF-8编码:[x{4e00}-x{9fa5}]+/u
$str = "学习php是一件快乐的事。"; preg_match_all("/[x80-xff]+/", $str, $match); //UTF-8 使用: //preg_match_all("/[x{4e00}-x{9fa5}]+/u", $str, $match); print_r($match);

Array
    [0] => Array