为了账号安全,请及时绑定邮箱和手机立即绑定

将 preg_match() 结果与 (bool) 一起使用?

将 preg_match() 结果与 (bool) 一起使用?

PHP
慕标琳琳 2022-12-30 17:39:15
我想我会使用preg_match()with的结果(bool),但我不太确定。我觉得不清楚结果是不是true还是false。示例 1:if (((bool) preg_match($pattern, $string, $matches)) === true)示例 2:if (((bool) !preg_match($pattern, $string, $matches)) === true)示例 3:if (((bool) preg_match($pattern, $string, $matches)) === false)示例 4:if (((bool) !preg_match($pattern, $string, $matches)) === false)另一种想法是:有结果的事情将来也安全吗0?1你有这方面的经验吗?你能报告什么?编辑 0:鉴于if没有比较运算符,问题得到了扩展。0总是false和1总是true?_示例 5:if ((preg_match($pattern, $string, $matches)))示例 6:if ((!preg_match($pattern, $string, $matches)))这个对吗?(preg_match($pattern, $string, $matches))= 0| 1(!preg_match($pattern, $string, $matches))= true| false不是!
查看完整描述

1 回答

?
30秒到达战场

TA贡献1828条经验 获得超6个赞

preg_match() 如果模式与给定主题匹配则返回 1,如果不匹配则返回 0,如果发生错误则返回 FALSE。这是 3 个可能的答案。如果将其简化为布尔值 (true/false),则会丢失一些信息。


$result = (bool) preg_match($pattern, $string, $matches);

$result 如果模式匹配则为真,否则为假或发生错误。


此 if 条件仅在 preg_match 返回 1 时执行。


if (preg_match($pattern, $string, $matches)) {


}

如果不执行可能不匹配或出错。


必须进行严格比较才能区分所有 3 种变体:


$preg_match_result = preg_match($pattern, $string, $matches);


if($preg_match_result === 1) {

  //pattern matches


}

elseif($preg_match_result === 0) {

  //pattern not matches


}

else {

  //$preg_match_result === false   

  //an error occurred


}


查看完整回答
反对 回复 2022-12-30
  • 1 回答
  • 0 关注
  • 104 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号