【问题标题】:Use preg_match() result with (bool)?将 preg_match() 结果与 (bool) 一起使用?
【发布时间】:2020-04-19 19:57:18
【问题描述】:

我想我会将preg_match() 的结果与(bool) 一起使用,但我不太确定。我认为不清楚结果不是truefalse。 示例 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
不是!

【问题讨论】:

  • 为什么?只需使用if (preg_match($pattern, $string, $matches)) { do sth }
  • @WiktorStribiżew,我也有同样的想法。我有我的问题扩展这个。因为不清楚。

标签: php boolean preg-match


【解决方案1】:

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

}

【讨论】:

    猜你喜欢
    • 2011-03-11
    • 1970-01-01
    • 2020-08-29
    • 1970-01-01
    • 2010-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-21
    相关资源
    最近更新 更多