1. int preg_match ( string $pattern
, string $subject
[, array &$matches
[, int $flags
= 0 [, int $offset
= 0 ]]] )
<?php $title = "Replacement Canon BP-511 Camcorder Battery [Item ID:3-236-523]"; if( preg_match("/([Item ID:)([0-9]+)-([0-9]+)-([0-9]+)(])/i",$title,$arr) ){ echo "<pre>"; print_r($arr); echo "</pre>"; } ?>
//返回结果是 Array ( [0] => [Item ID:3-236-523] [1] => [Item ID: [2] => 3 [3] => 236 [4] => 523 [5] => ] )
<?php // 下面的例子演示了将文本中所有 <pre></pre> 标签内的关键字(php)显示为红色。 $str = "<pre>学习php是一件快乐的事。</pre><pre>所有的phper需要共同努力!</pre>"; $kw = "php"; preg_match_all('/<pre>([sS]*?)</pre>/', $str, $mat); $length = count($mat[0]); for ($i=0; $i<$length; $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; ?>
特点:返回0或1 ,仅对$subject 匹配一次,若符合
$pattern则返回1,否则返回0;
$matches:数组类型,$matches[0]:匹配到的全部字符,$matches[1]...:此内容是其字表达式内匹配到的字符串( );
preg_match() returns the number of times pattern
matches. That will be either 0 times (no match) or 1 time because preg_match() will stop searching after the first match.
//实例 <?php // 从 URL 中取得主机名 preg_match("/^(http://)?([^/]+)/i", "http://www.php.net/index.html", $matches); $host = $matches[2]; echo $host; // 从主机名中取得后面两段 preg_match("/[^./]+.[^./]+$/", $host, $matches); echo "domain name is: {$matches[0]} "; // 本例执行后将输出: domain name is: php.net ?>
2. int preg_match_all ( string $pattern
, string $subject
[, array &$matches
[, int $flags
= PREG_PATTERN_ORDER
[, int $offset
= 0 ]]] )
Return Values :Returns the number of full pattern matches (which might be zero), or FALSE
if an error occurred.
<?php preg_match_all ("|<[^>]+>(.*)</[^>]+>|U", "<b>example: </b><div align=left>this is a test</div>",$out, PREG_PATTERN_ORDER); // 注意PREG_PATTERN_ORDER和PREG_SET_ORDER的区别 print $out[0][0].", ".$out[0][1]." "; print $out[1][0].", ".$out[1][1]." "; echo "<pre>"; print_r($out); ?>
//返回的结果 <b>example: </b>, <div align=left>this is a test</div> example: , this is a test <pre>Array ( [0] => Array ( [0] => <b>example: </b> //第一次匹配到的内容 [1] => <div align=left>this is a test</div> //第二次匹配到的内容 ) [1] => Array ( [0] => example: //第一次匹配到的值表达式的内容"(.*)"
[1] => this is a test//第二次匹配到的值表达式的内容"(.*)"
) )
与preg_match区别是:全部匹配 $subject,直到没有符合规则(
$pattern)为止。
注意PREG_PATTERN_ORDER和PREG_SET_ORDER的区别:
PREG_PATTERN_ORDER:将匹配的全部内容放在$match[0][] ; 将子表达式的内容放在 $match[1][];按序放置。
PREG_SET_ORDER :将匹配到的内容和子表达式的内容放在同一维数组中 $match[][].
3. preg_replace :按规则 搜索并替换。注意后向引用。
$subject = 'this hs 7 words and 31 letters'; $result = preg_replace(array('/d+/','/[a-z]+/'), array('num<