PHP preg_match()进行正则表达式匹配

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

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


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


1、eg

 
 
  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、eg匹配字符串中的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. )


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值