PHP正则 preg_match()

定义和用法

preg_match() 函数用于进行正则表达式匹配,成功返回 1 ,否则返回 0 。

preg_match() 匹配成功一次后就会停止匹配,如果要实现全部结果的匹配,则需使用 preg_match_all() 函数。

语法

 
  1. preg_match (pattern , subject, matches)
参数 描述
pattern 正则表达式
subject 需要匹配检索的对象
matches 可选,存储匹配结果的数组

例子 1

 
  1. <?php
  2. // 模式定界符后面的 "i" 表示不区分大小写字母的搜索
  3. if (preg_match ("/hi/i", "Welcome to hi-docs.com.")) {
  4. echo "A match was found.";
  5. } else {
  6. echo "A match was not found.";
  7. }
  8. ?>

输出:

 
  1. A match was found.

例子 2

匹配字符串中的url超链接

 
  1. <?php
  2. $urls = '<h3><a target="_blank" href="/php/preg_match.html"><span class="hl">preg</span>_match()</a></h3><p>[<a href="/Php.html">PHP</a>] 进行正则表达式匹配<br/><em>适用版本:5</em></p></dd><dd><h3><a target="_blank" href="/php/preg_match_all.html"><span class="hl">preg</span>_match_all()</a></h3>';
  3. if(preg_match("/<a[^>]*?href=\"([^>]+?)\"[^>]*?>.+?<\/a>/i", $urls ,$match)) {
  4. print_r($match);
  5. } else {
  6. echo "不匹配.";
  7. }
  8. ?>

输出:

 
  1. Array
  2. (
  3. [0] => <a target="_blank" href="/php/preg_match.html"><span class="hl">preg</span>_match()</a>
  4. [1] => /php/preg_match.html
  5. )

例子3

使用正则表达式匹配中文

 
  1. $str = 'preg_match正则匹配中文123';
  2. // 正则表达式匹配中文(UTF8编码)
  3. if(preg_match('/[\x{4e00}-\x{9fa5}]+/u',$str)){
  4. echo '匹配';
  5. }else{
  6. echo '没有匹配';
  7. }
  8. // 正则表达式匹配中文(GB2312,GBK编码)
  9. preg_match("/^[".chr(0xa1)."-".chr(0xff)."A-Za-z0-9_]+$/",$str);

猜你喜欢

转载自blog.csdn.net/echo_hello_world/article/details/82761125