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

我想我会使用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)

另一种想法是:有结果的事情将来也安全吗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))01
(!preg_match($pattern, $string, $matches))truefalse
不是!


慕标琳琳
浏览 105回答 1
1回答

30秒到达战场

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}
打开App,查看更多内容
随时随地看视频慕课网APP