php - 将 preg_match() 结果与 (bool) 一起使用?
问题描述
我想我会使用preg_match()
with的结果(bool)
,但我不太确定。我认为结果不是true
or并不清楚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
是不是!
解决方案
如果模式匹配给定的主题,preg_match() 返回 1,如果不匹配,则返回 0,如果发生错误,则返回 FALSE。这是3个可能的答案。如果将其减少为布尔值(真/假),则会丢失一些信息。
$result = (bool) preg_match($pattern, $string, $matches);
如果模式匹配,则 $result 为 true,如果不匹配或发生错误,则为 false。
此 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
}
推荐阅读
- python - 从一个表中提取小时值并在另一个表中填充一小时增量的“桶”的函数
- spock - 如何从 spock 测试框架访问 application.yml 文件
- mysql - 计算数据类型 TIME 的十进制数
- java - 在 Android API28 上关闭应用程序时,WorkManager 不会定期运行
- javascript - 在 JavaScript 中实现节点存储功能
- angular - 如何使用 PrimeNg 拖放保留列表 A 中已从列表 A 拖放到列表 B 中的元素?
- python-2.7 - 无法在 Google App Engine Standard 上导入 cygrpc
- c - 在 C 中实现 Shell:输出重定向是将输出文件名写入输出文件而不是命令结果
- python - 是否可以从单独的模块加载 SqlAlchemy 表定义而不会导致“未使用的导入语句”?
- powershell - 使用 Powershell 从 AD 中提取属性