首页 > 解决方案 > 将 preg_match() 结果与 (bool) 一起使用?

问题描述

我想我会使用preg_match()with的结果(bool),但我不太确定。我认为结果不是trueor并不清楚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)

另一个思考是:有结果的东西,未来也安全吗01你有经验吗?你能报告什么?

编辑0:鉴于if没有比较运算符,问题扩大了。是0永远false1永远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
是不是!

标签: phpbooleanpreg-match

解决方案


如果模式匹配给定的主题,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

}

推荐阅读