【问题标题】:preg_match_all for a stringpreg_match_all 用于字符串
【发布时间】:2013-08-21 04:39:27
【问题描述】:

我希望从这个字符串中获取America/Chicago

Local Time Zone (America/Chicago (CDT) offset -18000 (Daylight))

让它适用于其他时区,例如America/Los_AngelesAmerica/New_York 等等。我对prey_match_all 不是很好,而且,如果有人可以指导我学习如何正确学习它的好教程,因为这是我第三次需要使用它。

【问题讨论】:

标签: php string preg-match preg-match-all


【解决方案1】:

这是您使用我的正则表达式的解决方案

代码

    $in = "Local Time Zone (America/Chicago (CDT) offset -18000 (Daylight))";
    preg_match_all('/\(([A-Za-z0-9_\W]+?)\\s/', $in, $out);
    echo "<pre>";
    print_r($out[1][0]);

 ?>

还有输出

America/Chicago

希望这对你有帮助。

【讨论】:

  • 它对我有用,如果我的回答对你有用,请不要忘记投票并接受它。我会很高兴。
  • 如果你明年六月以后还在休斯顿,我给你买啤酒。谢谢!像魅力一样工作
  • @Fabian Buentello,非常感谢。
  • 它不适用于像 America/Los_Angeles 这样的时区,因为下划线在您的字符类中不匹配。
  • @M42,请查看我更新的答案。感谢您的建议。
【解决方案2】:

我会使用正则表达式:\((\S+)

preg_match_all('/\((\S+)/', $in, $out);

解释:

The regular expression:

(?-imsx:\((\S+))

matches as follows:

NODE                     EXPLANATION
----------------------------------------------------------------------
(?-imsx:                 group, but do not capture (case-sensitive)
                         (with ^ and $ matching normally) (with . not
                         matching \n) (matching whitespace and #
                         normally):
----------------------------------------------------------------------
  \(                       '('
----------------------------------------------------------------------
  (                        group and capture to \1:
----------------------------------------------------------------------
    \S+                      non-whitespace (all but \n, \r, \t, \f,
                             and " ") (1 or more times (matching the
                             most amount possible))
----------------------------------------------------------------------
  )                        end of \1
----------------------------------------------------------------------
)                        end of grouping
----------------------------------------------------------------------

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-12-11
    • 2018-05-07
    • 2022-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多