【问题标题】:Can anyone explain to me what this preg_match() function does?谁能向我解释这个 preg_match() 函数的作用?
【发布时间】:2011-03-21 19:08:24
【问题描述】:

所以我正在阅读这本关于 PHP 面向对象编程的书,在作者检查数据类型的示例方法中,我遇到了这个函数:

//class AddressManager...
function outputAddresses( $resolve ) {
  if ( is_string( $resolve ) ) {
    $resolve =
      ( preg_match("/false|no|off/i", $resolve ) )?
      false:true;
  }
  // ...
}

谁能告诉我它的目的是什么?属性无关紧要,但它是一种旨在将字符串转换为布尔值的方法(我认为)。

【问题讨论】:

    标签: php function methods


    【解决方案1】:

    preg_match 本身不会将字符串转换为布尔值,它是一个正则表达式匹配函数。你所拥有的是一个三元表达式,它的计算结果几乎是这样的:

    class AddressManager
    ... 
        function outputAddresses( $resolve ) 
        { 
        if ( is_string( $resolve ) ) 
        { 
          if (preg_match("/false|no|off/i", $resolve))
          {
             $resolve = false;
          } else {
             $resolve = true;
          }
          // $resolve = ( preg_match("/false|no|off/i", $resolve ) )? false:true; 
        } 
    // ... 
    }
    

    【讨论】:

      【解决方案2】:

      如果变量 $resolve 以不敏感的方式(忽略大小写)包含“false”或“no”或“off”,则返回 FALSE。否则返回 TRUE。

      看起来像一个简单的用户输入检查器(不是一个很好的)。例如,如果您输入“nothing”或“now”会发生什么?

      【讨论】:

      • 好点在那里,但属性 $resolve 是从使用 simpleXML API 的 xml 设置文件中获取的,所以我猜该属性已经预先确定,不需要那么多错误捕获,谢谢不过回复这么快!洗澡的时间里有很多回复,我很喜欢这个网站!
      【解决方案3】:

      上面的伪代码。

      if( $resolve equals false  or no or off)
      then 
          set  $resolve as false
      else
          set  $resolve as true
      

      ? (三元运算符)只是替换上面的代码行。这就是幕后发生的事情。

      http://en.wikipedia.org/wiki/Ternary_operation

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-03-11
        • 1970-01-01
        • 1970-01-01
        • 2011-02-11
        • 2017-07-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多