【问题标题】:PHP find US state code in stringPHP在字符串中查找美国州代码
【发布时间】:2011-11-13 09:36:54
【问题描述】:

我的字符串格式如下:

“德克萨斯州休斯顿”-str1
“伊利诺伊州芝加哥” - str2
“华盛顿州西雅图”-str3

当给定上述每个 str1/str2/str3 时,我想提取“TX”、“IL”、“WA”,如果字符串中存在状态代码(即 2 个大写字母在字符串末尾)使用 PHP 和正则表达式.. 任何指针.. 我无法从提供给我的方法的所有字符串中可靠地提取此信息。

【问题讨论】:

  • 对于正则表达式,试试这个方便的工具:txt2re.com

标签: php regex


【解决方案1】:

试试/, [A-Z]{2}$/(如果不重要,请删除逗号)。

【讨论】:

  • 或者使用/, ([A-Z]{2})$/ 抢组而不是整场比赛。
【解决方案2】:

用途:

$stateCode=trim(end(array_filter(explode(',',$string))));

【讨论】:

    【解决方案3】:
    substr($string, -2); // returns the last 2 characters
    

    【讨论】:

      【解决方案4】:

      您不需要为此使用正则表达式。假设状态码只能出现在字符串的最后,你可以使用这个小函数:

      /**
       * Extracts the US state code from a string and returns it, otherwise
       * returns false.
       *
       * "Houston, TX" - returns "TX"
       * "TX, Houston" - returns false
       *
       * @return string|boolean
       */
      function getStateCode($string)
      {
          // I'm not familiar with all the state codes, you
          // should add them yourself.
          $codes = array('TX', 'IL', 'WA');
      
          $code = strtoupper(substr($string, -2));
      
          if(in_array($code, $codes))
          {
              return $code;
          }
          else
          {
              return false;
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2014-07-24
        • 1970-01-01
        • 1970-01-01
        • 2010-12-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-08-14
        • 2015-09-18
        相关资源
        最近更新 更多